如何序列化词典作为使用Json.Net其父对象的一部分 [英] How to serialize a Dictionary as part of its parent object using 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 或更高版本,你愿意从词典&LT改变你的字典的类型;字符串,字符串&GT;
到词典&LT;字符串,对象&gt;
,那么一个简单的办法来完成你想要的是在 [JsonExtensionData]
属性添加到您喜欢这本字典属性:
If you're using Json.Net 5.0 release 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屋!