简体   繁体   English

使用serde_json解析对象内的对象

[英]Parsing an object inside an object with serde_json

I am stuck, below is the JSON which I am receiving: 我被卡住了,下面是我收到的JSON:

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

I am bit confused on how my struct should look like to parse the attributes using the serde_json crate. 我对我的结构应该如何使用serde_json包解析属性感到困惑。 Below is what I currently 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()
}

I am getting an error message: 我收到一条错误消息:

thread 'main' panicked at 'called Result::unwrap() on an Err value: ErrorImpl { code: Message("missing field assest "), line: 0, column: 0 }', src/libcore/result.rs:860:4 线程'main'在' Err值'上调用' Result::unwrap() unwrap Result::unwrap()时出错:ErrorImpl {code:Message(“missing field assest ”),line:0,column:0}',src / libcore / result.rs: 860:4

I think you want a HashMap. 我想你想要一个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 操场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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