@@ -20,12 +20,19 @@ JSON parsing and serialization
2020# What is JSON?
2121
2222JSON (JavaScript Object Notation) is a way to write data in Javascript.
23- Like XML it allows one to encode structured data in a text format that can be read by humans easily.
24- Its native compatibility with JavaScript and its simple syntax make it used widely.
23+ Like XML, it allows to encode structured data in a text format that can be easily read by humans.
24+ Its simple syntax and native compatibility with JavaScript have made it a widely used format.
25+
26+ Data types that can be encoded are JavaScript types (see the `Json` enum for more details):
27+
28+ * `Boolean`: equivalent to rust's `bool`
29+ * `Number`: equivalent to rust's `f64`
30+ * `String`: equivalent to rust's `String`
31+ * `Array`: equivalent to rust's `Vec<T>`, but also allowing objects of different types in the same
32+ array
33+ * `Object`: equivalent to rust's `Treemap<String, json::Json>`
34+ * `Null`
2535
26- Json data are encoded in a form of "key":"value".
27- Data types that can be encoded are JavaScript types :
28- boolean (`true` or `false`), number (`f64`), string, array, object, null.
2936An object is a series of string keys mapping to values, in `"key": value` format.
3037Arrays are enclosed in square brackets ([ ... ]) and objects in curly brackets ({ ... }).
3138A simple JSON document encoding a person, his/her age, address and phone numbers could look like:
@@ -49,105 +56,20 @@ A simple JSON document encoding a person, his/her age, address and phone numbers
4956
5057# Rust Type-based Encoding and Decoding
5158
52- Rust provides a mechanism for low boilerplate encoding & decoding
53- of values to and from JSON via the serialization API.
59+ Rust provides a mechanism for low boilerplate encoding & decoding of values to and from JSON via
60+ the serialization API.
5461To be able to encode a piece of data, it must implement the `serialize::Encodable` trait.
5562To be able to decode a piece of data, it must implement the `serialize::Decodable` trait.
56- The Rust compiler provides an annotation to automatically generate
57- the code for these traits: `#[deriving(Decodable, Encodable)]`
58-
59- To encode using Encodable :
60-
61- ```rust
62- use std::io;
63- use serialize::{json, Encodable};
64-
65- #[deriving(Encodable)]
66- pub struct TestStruct {
67- data_str: String,
68- }
69-
70- fn main() {
71- let to_encode_object = TestStruct{data_str:"example of string to encode".to_string()};
72- let mut m = io::MemWriter::new();
73- {
74- let mut encoder = json::Encoder::new(&mut m as &mut Writer);
75- match to_encode_object.encode(&mut encoder) {
76- Ok(()) => (),
77- Err(e) => fail!("json encoding error: {}", e)
78- };
79- }
80- }
81- ```
82-
83- Two wrapper functions are provided to encode a Encodable object
84- into a string (String) or buffer (vec![u8]): `str_encode(&m)` and `buffer_encode(&m)`.
63+ The Rust compiler provides an annotation to automatically generate the code for these traits:
64+ `#[deriving(Decodable, Encodable)]`
8565
86- ```rust
87- use serialize::json;
88- let to_encode_object = "example of string to encode".to_string();
89- let encoded_str: String = json::Encoder::str_encode(&to_encode_object);
90- ```
91-
92- JSON API provide an enum `json::Json` and a trait `ToJson` to encode object.
93- The trait `ToJson` encode object into a container `json::Json` and the API provide writer
94- to encode them into a stream or a string ...
66+ The JSON API provides an enum `json::Json` and a trait `ToJson` to encode objects.
67+ The `ToJson` trait provides a `to_json` method to convert an object into a `json::Json` value.
68+ A `json::Json` value can be encoded as a string or buffer using the functions described above.
69+ You can also use the `json::Encoder` object, which implements the `Encoder` trait.
9570
9671When using `ToJson` the `Encodable` trait implementation is not mandatory.
9772
98- A basic `ToJson` example using a TreeMap of attribute name / attribute value:
99-
100-
101- ```rust
102- use std::collections::TreeMap;
103- use serialize::json;
104- use serialize::json::ToJson;
105-
106- pub struct MyStruct {
107- attr1: u8,
108- attr2: String,
109- }
110-
111- impl ToJson for MyStruct {
112- fn to_json( &self ) -> json::Json {
113- let mut d = box TreeMap::new();
114- d.insert("attr1".to_string(), self.attr1.to_json());
115- d.insert("attr2".to_string(), self.attr2.to_json());
116- json::Object(d)
117- }
118- }
119-
120- fn main() {
121- let test2: MyStruct = MyStruct {attr1: 1, attr2:"test".to_string()};
122- let tjson: json::Json = test2.to_json();
123- let json_str: String = tjson.to_str().into_string();
124- }
125- ```
126-
127- To decode a JSON string using `Decodable` trait :
128-
129- ```rust
130- extern crate serialize;
131- use serialize::{json, Decodable};
132-
133- #[deriving(Decodable)]
134- pub struct MyStruct {
135- attr1: u8,
136- attr2: String,
137- }
138-
139- fn main() {
140- let json_str_to_decode: String =
141- "{\"attr1\":1,\"attr2\":\"toto\"}".to_string();
142- let json_object = json::from_str(json_str_to_decode.as_slice());
143- let mut decoder = json::Decoder::new(json_object.unwrap());
144- let decoded_object: MyStruct = match Decodable::decode(&mut decoder) {
145- Ok(v) => v,
146- Err(e) => fail!("Decoding error: {}", e)
147- }; // create the final object
148- }
149- ```
150-
15173# Examples of use
15274
15375## Using Autoserialization
@@ -157,41 +79,37 @@ using the serialization API, using the derived serialization code.
15779
15880```rust
15981extern crate serialize;
160- use serialize::{ json, Encodable, Decodable} ;
82+ use serialize::json;
16183
162- #[deriving(Decodable, Encodable)] //generate Decodable, Encodable impl.
163- pub struct TestStruct1 {
84+ #[deriving(Decodable, Encodable)] //generate Decodable, Encodable impl.
85+ pub struct TestStruct1 {
16486 data_int: u8,
16587 data_str: String,
16688 data_vector: Vec<u8>,
167- }
89+ }
16890
169- // To serialize use the `json::str_encode` to encode an object in a string.
170- // It calls the generated `Encodable` impl.
17191fn main() {
172- let to_encode_object = TestStruct1
92+ let object = TestStruct1
17393 {data_int: 1, data_str:"toto".to_string(), data_vector:vec![2,3,4,5]};
174- let encoded_str: String = json::Encoder::str_encode(&to_encode_object);
17594
176- // To deserialize use the `json::from_str` and `json::Decoder`
95+ // Serialize using `json::encode`
96+ let encoded = json::encode(&object);
17797
178- let json_object = json::from_str(encoded_str.as_slice());
179- let mut decoder = json::Decoder::new(json_object.unwrap());
180- let decoded1: TestStruct1 = Decodable::decode(&mut decoder).unwrap(); // create the final object
98+ // Deserialize using `json::decode`
99+ let decoded: TestStruct1 = json::decode(encoded.as_slice()).unwrap();
181100}
182101```
183102
184103## Using `ToJson`
185104
186- This example uses the ToJson impl to deserialize the JSON string.
187- Example of `ToJson` trait implementation for TestStruct1.
105+ This example uses the `ToJson` trait to generate the JSON string.
188106
189107```rust
190108use std::collections::TreeMap;
191109use serialize::json::ToJson;
192- use serialize::{ json, Encodable, Decodable} ;
110+ use serialize::json;
193111
194- #[deriving(Decodable, Encodable)] // generate Decodable, Encodable impl.
112+ #[deriving(Decodable)]
195113pub struct TestStruct1 {
196114 data_int: u8,
197115 data_str: String,
@@ -200,7 +118,7 @@ pub struct TestStruct1 {
200118
201119impl ToJson for TestStruct1 {
202120 fn to_json( &self ) -> json::Json {
203- let mut d = box TreeMap::new();
121+ let mut d = TreeMap::new();
204122 d.insert("data_int".to_string(), self.data_int.to_json());
205123 d.insert("data_str".to_string(), self.data_str.to_json());
206124 d.insert("data_vector".to_string(), self.data_vector.to_json());
@@ -209,19 +127,13 @@ impl ToJson for TestStruct1 {
209127}
210128
211129fn main() {
212- // Serialization using our impl of to_json
213-
214- let test2: TestStruct1 = TestStruct1 {data_int: 1, data_str:"toto".to_string(),
215- data_vector:vec![2,3,4,5]};
130+ // Serialize using `ToJson`
131+ let test2 = TestStruct1 {data_int: 1, data_str:"toto".to_string(), data_vector:vec![2,3,4,5]};
216132 let tjson: json::Json = test2.to_json();
217- let json_str: String = tjson.to_str().into_string();
218-
219- // Deserialize like before.
133+ let json_str: String = tjson.to_str();
220134
221- let mut decoder =
222- json::Decoder::new(json::from_str(json_str.as_slice()).unwrap());
223- // create the final object
224- let decoded2: TestStruct1 = Decodable::decode(&mut decoder).unwrap();
135+ // Deserialize like before
136+ let decoded: TestStruct1 = json::decode(json_str.as_slice()).unwrap();
225137}
226138```
227139
@@ -1058,7 +970,8 @@ impl Stack {
1058970 match * self . stack . get ( idx) {
1059971 InternalIndex ( i) => { Index ( i) }
1060972 InternalKey ( start, size) => {
1061- Key ( str:: from_utf8 ( self . str_buffer . slice ( start as uint , ( start+size) as uint ) ) . unwrap ( ) )
973+ Key ( str:: from_utf8 (
974+ self . str_buffer . slice ( start as uint , start as uint + size as uint ) ) . unwrap ( ) )
1062975 }
1063976 }
1064977 }
0 commit comments