如何在具有可变键名的 json 对象上使用 serde json

How can I use serde json on a json object with variable key names

我知道 JSON 值可用于未知 JSON。

我拥有的是一个主要结构化的 JSON 对象,如下所示:

{
    "error": [],
    "result": {
        "NAME_X": {
            "prop_one": "something",
            "prop_two": "something",
            "decimals": 1,
            "more_decimals": 2
        },
        "NAME_A": {
            "prop_one": "test",
            "prop_two": "sdfsdf",
            "decimals": 2,
            "more_decimals": 5
        },
        "ARBITRARY": {
            "prop_one": "something else",
            "prop_two": "blah",
            "decimals": 3,
            "more_decimals": 6
        }
}

因此具有prop_one、prop_two、小数和more_decimals字段的内部对象具有清晰的结构,但外部名称field/key(NAME_X , NAME_A, ARBITRARY) 事先未知。

最直接的解析方法是什么,以便我可以在内部结构上使用强类型 variables/deserialization?我还需要捕获那些未知的名称字段。

您可以反序列化为键为字符串("NAME_X" 等)的映射:

use std::collections::HashMap;
use serde::Deserialize;
use serde_json::Result;

#[derive(Debug, Deserialize)]
struct InThing {
    prop_one: String,
    prop_two: String,
    decimals: u16,
    more_decimals: i32,
}
#[derive(Debug, Deserialize)]
struct OutThing {
    error: Vec<u8>,
    result: HashMap<String, InThing>,
}

fn main() {
    let data = r#"
        {
            "error": [],
            "result": {
                "NAME_X": {
                    "prop_one": "something",
                    "prop_two": "something",
                    "decimals": 1,
                    "more_decimals": 2
                },
                "NAME_A": {
                    "prop_one": "test",
                    "prop_two": "sdfsdf",
                    "decimals": 2,
                    "more_decimals": 5
                },
                "ARBITRARY": {
                    "prop_one": "something else",
                    "prop_two": "blah",
                    "decimals": 3,
                    "more_decimals": 6
                }
            }
        }
        "#;
    let thing: OutThing = serde_json::from_str(data).unwrap(); 
    dbg!(thing);
}

playground