-A basic `ToJson` example using a TreeMap of attribute name / attribute value:
-
-
-```rust
-use std::collections::TreeMap;
-use serialize::json;
-use serialize::json::ToJson;
-
-pub struct MyStruct {
- attr1: u8,
- attr2: String,
-}
-
-impl ToJson for MyStruct {
- fn to_json( &self ) -> json::Json {
- let mut d = box TreeMap::new();
- d.insert("attr1".to_string(), self.attr1.to_json());
- d.insert("attr2".to_string(), self.attr2.to_json());
- json::Object(d)
- }
-}
-
-fn main() {
- let test2: MyStruct = MyStruct {attr1: 1, attr2:"test".to_string()};
- let tjson: json::Json = test2.to_json();
- let json_str: String = tjson.to_str().into_string();
-}
-```
-
-To decode a JSON string using `Decodable` trait :
-
-```rust
-extern crate serialize;
-use serialize::{json, Decodable};
-
-#[deriving(Decodable)]
-pub struct MyStruct {
- attr1: u8,
- attr2: String,
-}
-
-fn main() {
- let json_str_to_decode: String =
- "{\"attr1\":1,\"attr2\":\"toto\"}".to_string();
- let json_object = json::from_str(json_str_to_decode.as_slice());
- let mut decoder = json::Decoder::new(json_object.unwrap());
- let decoded_object: MyStruct = match Decodable::decode(&mut decoder) {
- Ok(v) => v,
- Err(e) => fail!("Decoding error: {}", e)
- }; // create the final object
-}
-```
-