如何在Serde中(反)序列化强类型的JSON词典? [英] How to (de)serialize a strongly typed JSON dictionary in Serde?

查看:178
本文介绍了如何在Serde中(反)序列化强类型的JSON词典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个Rust应用程序,该应用程序使用公共接口处理来自TypeScript客户端的JSON消息.我已经使用serde_derive编写了一些代码,并且效果很好,但是我不知道如何实现字典.例如:

I am writing a Rust application that handles JSON messages from a TypeScript client with a public interface. I have written some code using serde_derive and it works well, but I can't figure out how to implement dictionaries; e.g.:

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

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

Here the keys are the strings "foo" and "bar" and the dictionary's values follow this schema:

use serde_derive;
use serde_json::Number;

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

我正在以这种方式访问​​JSON数据:

I am looking to access the JSON data in this manner:

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

如何使用Serde将JSON数据反序列化到Dictionary中或从Dictionary反序列化?

How can I (de)serialize my JSON data into/from Dictionary using Serde?

推荐答案

您的代码中存在逻辑错误. JSON文件中的结构描述了一个关联数组,但是您的Dictionary不支持多个键值对.如 Stargateur在评论中所述 ,您可以使用 HashMap ,因为Serde具有 HashMap SerializeDeserialize实现.

You have a logic error in your code. The structure in your JSON file describes an associative array but your Dictionary does not support multiple key-value-pairs. As Stargateur stated in the comments, you may use HashMap as Serde has Serialize and Deserialize implementations for HashMap.

您可以将Dictionary重写为

type Dictionary = HashMap<String, DictionaryValue>;

您可以例如通过以下方式检索数据

and you can retrieve the data for example by

let dict: Dictionary = serde_json::from_str(json_string).unwrap();

如果您现在想将所有内容包装在Dictionary-结构中,它将看起来像这样:

If you now want to wrap everything in a Dictionary-struct it will look like this:

#[derive(Serialize, Deserialize)]
struct Dictionary {
    inner: HashMap<String, DictionaryValue>,
}

问题是serde_json现在期望

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

要消除此问题,可以将serde(flatten) 属性添加到Dictionary:

To get rid of this, you can add the serde(flatten) attribute to Dictionary:

#[derive(Serialize, Deserialize, Debug)]
struct Dictionary {
    #[serde(flatten)]
    inner: HashMap<String, DictionaryValue>,
}

如果 HashMap 或任何std中的="https://doc.rust-lang.org/std/collections/struct.BTreeMap.html" rel ="nofollow noreferrer"> BTreeMap 不符合您的需求,您可以还可以自己实现Dictionary.请参见文档此处

If HashMap or any BTreeMap from std does not fit your needs, you can also implement your Dictionary on your own. See the docs here and here for more details.

这篇关于如何在Serde中(反)序列化强类型的JSON词典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆