I am exploring Json serialization in Rust, specifically how to serialize Rust objects for Json.
I currently see 3 methods for converting an instance of a structure to Json:
Obtaining an encoded attribute
Manual implementation of the ToJson trait
Manual implementation of an encoded attribute
The code below illustrates all 3 approaches:
extern crate serialize; use serialize::{Encoder, Encodable, json}; use serialize::json::{Json, ToJson}; use std::collections::TreeMap; fn main() { let document = Document::new(); let word_document = WordDocument::new(); println!("1. Deriving `Encodable`: {}", json::encode(&document)); println!("2. Manually implementing `ToJson` trait: {}", document.to_json()); println!("3. Manually implementing `Encodable` trait: {}", json::encode(&word_document)); }
Rusty Playpen: http://is.gd/r7cYmE
Results:
1. Deriving `Encodable`: {"metadata":[["Title","Untitled Document 1"]]} 2. Manually implementing `ToJson` trait: {"Title":"Untitled Document 1"} 3. Manually implementing `Encodable` trait: {"Title":"Untitled Word Document 1"}
The first method is fully automatic, but does not provide sufficient flexibility. The second and third achieve the same level of flexibility by specifying a manual serialization process. In my case, I want the document metadata to be serialized as an object, and not as an array (this is what the implementation gives me).
Questions
- Why are there methods 2 and 3? I do not understand the reason for the overlap between them. I expect that there is only one automatic (output) serialization method and one manual.
If I need manual serialization, which method to choose and why?
Do I believe that method 2 will build in memory (
) an enumerated number of Json (besides the structure itself) and is worse suited for large documents (several megabytes), while method 3 is streaming and safe for large documents?Why does stdlib rust use method 3 even for primitives but not use method 2 internally?
json serialization rust
Valentin
source share