0
votes

I am trying to deserialize JSON that is received from Web API and has some unnecessarily deep structure.

With serde, is it possible to deserialize JSON like:

{
    "unnecessarily": {
        "deep": {
            "structure": {
                "data1": 0
            }
        }
    },
    "data2": 0
}

to rust struct:

struct Data {
   data1: usize,
   data2: usize,
}

without manually implementing Deserialize?

If it is impossible, are there any other suitable crates?

1
You can define several structs that mimic the structure of your JSON, then use the from tag to convert automatically into the flat struct. - Jmb

1 Answers

2
votes

You can use serde's derive macro to generate implementations of Serialize and Deserialize traits

use serde::Deserialize;

#[derive(Deserialize)]
struct Data {
   data1: usize,
   data2: usize,
}

If the JSON structure is not known ahead of time, you can deserialize to serde_json::Value and work with this

use serde_json::{Result, Value};
fn example() -> Result<()> {
    let data = r#"
        {
          "unnecessarily": {
            "deep": {
              "structure": {
                "data1": 0
              }
            }
          },
          "data2": 0
        }"#;

    let v: Value = serde_json::from_str(data)?;

    let data1 = v["unnecessarily"]["deep"]["structure"]["data1"].as_i64()?;

    Ok(())
}