Skip to main content

simple/
simple.rs

1use nanojson::{Deserialize, Serialize};
2
3#[derive(Serialize, Deserialize, Debug)]
4struct MyStruct {
5    #[nanojson(default)]
6    num: i32,
7    #[nanojson(default)]
8    name: String,
9}
10
11fn main() {
12    // Parse a JSON string into a struct
13    let json = r#"{}"#;
14    let my_struct = nanojson::parse::<MyStruct>(json);
15
16    if let Err(ref e) = my_struct { e.print(json); }
17    if let Ok(mut my_struct) = my_struct {
18        println!("Parsed: {:?}", my_struct);
19
20        // Change the fields and turn back into a JSON string again
21        my_struct.num = 420;
22        my_struct.name = "world".to_string();
23        if let Ok(json) = nanojson::stringify(&my_struct) {
24            println!("JSON: {}", json);
25        }
26    }
27}