您的代码中有逻辑错误。 JSON 文件中的结构描述了一个关联数组,但您的Dictionary
不支持多个键值对。作为Stargateur在评论中指出 https://stackoverflow.com/questions/49717966/how-to-deserialize-a-strongly-typed-json-dictionary-in-serde#comment86448934_49717966,你可以使用HashMap https://doc.rust-lang.org/std/collections/struct.HashMap.html as Serde
has Serialize
and Deserialize
的实现HashMap https://doc.rust-lang.org/std/collections/struct.HashMap.html.
您可以重写您的Dictionary
as
type Dictionary = HashMap<String, DictionaryValue>;
您可以通过以下方式检索数据
let dict: Dictionary = serde_json::from_str(json_string).unwrap();
如果您现在想将所有内容包装在Dictionary
-struct 它看起来像这样:
#[derive(Serialize, Deserialize)]
struct Dictionary {
inner: HashMap<String, DictionaryValue>,
}
问题是,serde_json
现在期望
{
"inner": {
"foo" : { "data" : 42 },
"bar" : { "data" : 1337 }
}
}
要摆脱这个问题,您可以添加serde(flatten)
属性 https://serde.rs/attributes.html to Dictionary
:
#[derive(Serialize, Deserialize, Debug)]
struct Dictionary {
#[serde(flatten)]
inner: HashMap<String, DictionaryValue>,
}
If HashMap https://doc.rust-lang.org/std/collections/struct.HashMap.html or any BTreeMap https://doc.rust-lang.org/std/collections/struct.BTreeMap.html from std
不符合您的需求,您也可以实现您的Dictionary
靠你自己。请参阅文档here https://serde.rs/impl-serialize.html#serializing-a-sequence-or-map and here https://serde.rs/impl-deserialize.html更多细节。