serde_json - how to make my struct convertable from / to json?
Asked Answered
B

2

5

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.

Bartholomeus answered 19/8, 2015 at 15:30 Comment(0)
D
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

Damnable answered 19/8, 2015 at 16:6 Comment(4)
it doesn't have the link to serde::Serialize, where did you get it?Bartholomeus
@jawanam It's defined in the serde crate here serde-rs.github.io/serde/serde/serde/index.htmlDamnable
It is, but it's not given in the documentation.Bartholomeus
@jawanam Yeah, I was confused a bit where they were defined too.Damnable
F
3

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
}
Formality answered 28/10, 2022 at 11:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.