Parsing an object inside an object using serde_json

I'm stuck, below is the JSON I get:

{
   "BCH": {
      "aclass": "currency",
      "altname": "BCH",
      "decimals": 10,
      "display_decimals": 5
   }
}

I'm a little confused about how my structure should look like to parse attributes using a box serde_json. Below is what I have:

#[derive(Deserialize, Debug)]
struct Assets  {  
    aclass: String,
    altname: String,
    decimals: u8,
    display_decimals: u8,
}

#[derive(Deserialize, Debug)]
struct Currency {
    assest: Assets,
}


fn to_assets_type(value: serde_json::Value) -> Currency {
 serde_json::from_value(value).unwrap()
}

The error message appears:

thread 'main' paniked at 'entitled Result::unwrap()to Errvalue: {ErrorImpl code: Message ( "missing field assest"), row 0, column: 0}', src / libcore / result.rs : 860: 4

+4
source share
1 answer

I think you want a HashMap.

#[macro_use] extern crate serde;
extern crate serde_json;

use std::collections::HashMap;

static VALUE: &str = r#"{
   "BCH": {
      "aclass": "currency",
      "altname": "BCH",
      "decimals": 10,
      "display_decimals": 5
   }
}"#;

#[derive(Deserialize, Debug)]
struct Assets {  
    aclass: String,
    altname: String,
    decimals: u8,
    display_decimals: u8,
}

fn main() {
    let serde_value: HashMap<String, Assets> = serde_json::from_str(VALUE).unwrap();

    println!("{:?}", serde_value);
}

playground

+6
source

Source: https://habr.com/ru/post/1685148/


All Articles