[英]Serialize a Dictionary as JSON object using DataContractJsonSerializer
I have an [DataContract]
object that has some properties and is serialized to JSON using DataContractJsonSerializer
.我有一个
[DataContract]
对象,它具有一些属性并使用DataContractJsonSerializer
序列化为 JSON。
One of the properties is of type Dictionary<string, string>
and when the serialization happens it produces the following JSON schema.其中一个属性是
Dictionary<string, string>
,当序列化发生时,它会生成以下 JSON 模式。
"extra_data": [
{
"Key": "aKey",
"Value": "aValue"
}
]
Now I need the JSON schema to be like this现在我需要 JSON 模式是这样的
"extra_data": {
"aKey": "aValue"
}
You can never of course know before what the values are, it is a Dictionary
that the user will set keys and values.您当然永远无法知道值是什么,它是用户将设置键和值的
Dictionary
。
I'm thinking if this can happen using anonymous types, or is there a configuration I can take to accomplish my goal?我在想这是否可以使用匿名类型发生,或者是否有我可以采取的配置来实现我的目标?
Thank you.谢谢。
Ok, let say you have:好吧,假设你有:
[DataContract]
public class MyObject
{
[DataMember(Name = "extra_data")]
public Dictionary<string, string> MyDictionary { get; set; }
}
Then you can use DataContractJsonSerializerSettings
with UseSimpleDictionaryFormat
set to true, something like this:然后您可以使用
DataContractJsonSerializerSettings
并将UseSimpleDictionaryFormat
设置为 true,如下所示:
var myObject = new MyObject { MyDictionary = new Dictionary<string, string> { { "key1", "value1" }, { "key2", "value2" } } };
DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings { UseSimpleDictionaryFormat = true };
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(MyObject), settings);
var result = string.Empty;
using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, myObject);
result = Encoding.Default.GetString(ms.ToArray());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.