如何在 Serde 中(反)序列化强类型 JSON 字典?

2024-05-17

我正在编写一个 Rust 应用程序,它使用公共接口处理来自 TypeScript 客户端的 JSON 消息。我写了一些代码使用serde_derive它运行良好,但我不知道如何实现字典;例如。:

{
  "foo" : { "data" : 42 },
  "bar" : { "data" : 1337 }
}

这里的键是字符串"foo" and "bar"并且字典的值遵循以下模式:

use serde_derive;
use serde_json::Number;

#[derive(Serialize, Deserialize)]
struct DictionaryValue {
    data: Number,
}

我希望以这种方式访问​​ JSON 数据:

#[derive(Serialize, Deserialize)]
struct Dictionary {
    key: String,
    value: DictionaryValue,
}

如何将我的 JSON 数据序列化(反序列化)到/从Dictionary使用塞尔德?


您的代码中有逻辑错误。 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更多细节。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Serde 中(反)序列化强类型 JSON 字典? 的相关文章

随机推荐