如何使用 Json.Net 将字典序列化为其父对象的一部分 [英] How to serialize a Dictionary as part of its parent object using Json.Net

查看:13
本文介绍了如何使用 Json.Net 将字典序列化为其父对象的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Json.Net 进行序列化.我有一个带字典的类:

I'm using Json.Net for serialization. I have a class with a Dictionary:

public class Test
{
    public string X { get; set; }

    public Dictionary<string, string> Y { get; set; }
}

我可以以某种方式序列化这个对象以获得以下 JSON

Can I somehow serialize this object to get the following JSON

{
    "X" : "value",
    "key1": "value1",
    "key2": "value2"
}

key1"、key2"是字典中的键吗?

where "key1", "key2" are keys in the Dictionary?

推荐答案

如果您使用 Json.Net 5.0.5 或更高版本,并且您愿意将字典的类型从 Dictionary 更改为 Dictionary,那么实现您想要的一种简单方法是将 [JsonExtensionData] 属性添加到您的字典属性中,如下所示:

If you're using Json.Net 5.0.5 or later and you're willing to change the type of your dictionary from Dictionary<string, string> to Dictionary<string, object>, then one easy way to accomplish what you want is to add the [JsonExtensionData] attribute to your dictionary property like this:

public class Test
{
    public string X { get; set; }

    [JsonExtensionData]
    public Dictionary<string, object> Y { get; set; }
}

被标记的字典的键和值将被序列化为父对象的一部分.好处是它也适用于反序列化:JSON 中与类成员不匹配的任何属性都将放入字典中.

The keys and values of the marked dictionary will then be serialized as part of the parent object. The bonus is that it works on deserialization as well: any properties in the JSON that do not match to members of the class will be placed into the dictionary.

这篇关于如何使用 Json.Net 将字典序列化为其父对象的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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