简体   繁体   中英

Deserializing different data structures with rust serde

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?

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(())
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM