Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In Rust, how can a JSON be deserialized in multiple structs?

Lets’ say we have the following JSON:

{
   name:"John",
   age:"30"
}

and the two following structs:

struct Name {
   name: String;
}

struct Age {
   age: i32
}

What would be an efficient way to deserialize this JSON into this structs?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Create a third struct containing each of the others and use #[serde(flatten)] to deserialize each field as if it’s a single flat struct:

use serde::Deserialize;

#[derive(Debug, Deserialize)]
struct Name {
    name: String,
}
#[derive(Debug, Deserialize)]
struct Age {
    age: i32,
}
#[derive(Debug, Deserialize)]
struct Person {
    #[serde(flatten)]
    name: Name,
    #[serde(flatten)]
    age: Age,
}

fn main() {
    dbg!(serde_json::from_str::<Person>(r#"{ "name": "John", "age": 30 }"#).unwrap());
    // Person {
    //     name: Name {
    //         name: "John",
    //     },
    //     age: Age {
    //         age: 30,
    //     },
    // }
}

playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading