4

我被卡住了,下面是我收到的 JSON:

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

我对我的结构应该如何使用serde_json板条箱解析属性感到有点困惑。以下是我目前拥有的:

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

我收到一条错误消息:

线程'main'在'调用Result::unwrap()一个Err 值:ErrorImpl { code:Message(“missing field assest”),line:0,column:0}'时惊慌失措,src/libcore/result.rs:860:4

4

1 回答 1

7

我想你想要一个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);
}

操场

于 2017-09-06T12:48:35.333 回答