I want to save data in a json file.
I know that I can use serde_json::to_string(&instance of struct).unwrap()
to serialize the whole struct. But as it is not necessary to save all data because some of the data in the struct keep their default value or will be overwritten anyway because they are process data, I would like to save only the parts which are necessary to keep.
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize, Debug)]
struct Data {
#[serde(default = "default_one")]
one: f64,
#[serde(default = "default_two")]
two: String,
#[serde(default = "default_three")]
three: bool,
}
fn default_one() -> f64 {
5.0
}
fn default_two() -> String {
String::from("This number serves as multiplier")
}
fn default_three() -> bool {
false
}
fn main() {
let new_data = r#"
{
"one": 10.0
}
"#;
let mut my_data:Data = serde_json::from_str(new_data).unwrap();
my_data.one = 5.0;
my_data.two = String::from("This number serves as numerator");
let serialized = serde_json::to_string(&my_data).unwrap();
println!("{}", serialized);
}
and this prints
{"one":5.0,"two":"This number serves as numerator","three":false}
But I want save only the parts that are not default.
What do I have to do to get only {"two":"This number serves as numerator"}
?