6

Looking at the documentation of serde_json, I can't understand what trait I have to implement to make a struct serializiable to and deserializiable from json. The obvious answer could be Deserializer and Serializer but these are structs, not traits.

With rustc-serialize I could implement ToJson and FromJson traits.

2 Answers 2

5

From the crate index page:

Serde provides a mechanism for low boilerplate serialization & deserialization of values to and from JSON via the serialization API. To be able to serialize a piece of data, it must implement the serde::Serialize trait. To be able to deserialize a piece of data, it must implement the serde::Deserialize trait. Serde provides provides an annotation to automatically generate the code for these traits: #[derive(Serialize, Deserialize)].

-- Creating Json by Serializing Data Structures

Sign up to request clarification or add additional context in comments.

4 Comments

it doesn't have the link to serde::Serialize, where did you get it?
@jawanam It's defined in the serde crate here serde-rs.github.io/serde/serde/serde/index.html
It is, but it's not given in the documentation.
@jawanam Yeah, I was confused a bit where they were defined too.
4

To deserialize a struct into a json file run a code similar to the following one :

let struct = Struct::create(); let slice_string_in_json_format = serde_json::to_string(&struct); 

Instead to serielize a json file component into a struct you can use a similar pattern:

fn parsing_json_into_struct() -> Result<Struct> { // Open the json file let mut file_content = match File::open("file.json") { Ok( file) => file, Err(_) => panic!("Could not read the json file") }; // Transform content of the file into a string let mut contents = String::new(); match file_content.read_to_string(&mut contents) { Ok(_) => {}, Err(err) => panic!("Could not deserialize the file, error code: {}", err) }; let module: Result<Struct> = serde_json::from_str(&contents.as_str()); module } 

Comments