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?
>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,
// },
// }
}