Hello community!
I am new to rust and am currently learning about the "serde" framework.
I ran into not being able to deserialize the JSON object back that I got when serializing my structure. It is a recursively nested "struct" with flatten fields.
Error:
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Error("invalid type: integer `20`, expected struct Person", line: 18, column: 1)', src/main.rs:28:75
Given that I would like to keep the "struct" and format of JSON, what do I need to fix with minimal changes using the capabilities of the framework?
Thank you in advance! The code and link to the playground are attached,
use std::collections::BTreeMap;
use serde::{Serialize, Deserialize};
use serde_json;
#[derive(Debug, Serialize, Deserialize)]
struct Person {
#[serde(flatten)]
reports: BTreeMap<String, Person>,
#[serde(flatten)]
subscriptions: BTreeMap<String, Subscription>,
}
#[derive(Debug, Serialize, Deserialize)]
struct Subscription {
cost: i32,
kind: String,
}
fn main() {
let person_obj = compose_person_example_struct();
println!("Object!\n{:?}\n", person_obj);
let person_obj_ser = serde_json::to_string_pretty(&person_obj).unwrap();
println!("Serialized!\n{}\n", person_obj_ser);
let person_obj_ser_de: Person = serde_json::from_str(&person_obj_ser).unwrap();
println!("Deserialized!\n{:?}\n", person_obj_ser_de);
}
fn compose_person_example_struct() -> Person {
/*
Returns object:
Person{
reports: {
"Pete": Person{
reports: {
"John": Person{
reports: { },
subscriptions: {
"Netflix": Subscription{cost: 20, kind: "movies"},
"Spotify": Subscription{cost: 10, kind: "music"}
}
}
},
subscriptions: {
"Spotify": Subscription{cost: 10, kind: "music"}
}
}
},
subscriptions: { }
}
*/
let mut john_subscriptions = BTreeMap::new();
john_subscriptions.insert("Netflix".to_string(), Subscription{kind: "movies".to_string(), cost: 20});
john_subscriptions.insert("Spotify".to_string(), Subscription{kind: "music".to_string(), cost: 10});
let mut pete_subscriptions = BTreeMap::new();
pete_subscriptions.insert("Spotify".to_string(), Subscription{kind: "music".to_string(), cost: 10});
let mut pete_reports = BTreeMap::new();
pete_reports.insert("John".to_string(), Person{reports: BTreeMap::new(), subscriptions: john_subscriptions});
let mut reports = BTreeMap::new();
reports.insert("Pete".to_string(), Person{reports: pete_reports, subscriptions: pete_subscriptions});
Person { reports, subscriptions: BTreeMap::new() }
}