使用DataContractJsonSerializer将Dictionary序列化为JSON对象 [英] Serialize a Dictionary as JSON object using DataContractJsonSerializer

查看:228
本文介绍了使用DataContractJsonSerializer将Dictionary序列化为JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个[DataContract]对象,该对象具有一些属性,并使用DataContractJsonSerializer序列化为JSON.

I have an [DataContract] object that has some properties and is serialized to JSON using DataContractJsonSerializer.

其中一个属性的类型为Dictionary<string, string>,当序列化发生时,它会生成以下JSON模式.

One of the properties is of type Dictionary<string, string> and when the serialization happens it produces the following JSON schema.

"extra_data": [
  {
    "Key": "aKey",
    "Value": "aValue"
  }
]

现在我需要这样的JSON模式

Now I need the JSON schema to be like this

"extra_data": { 
        "aKey": "aValue"
}

您当然永远不会知道这些值是什么,这是用户将设置键和值的Dictionary.

You can never of course know before what the values are, it is a Dictionary that the user will set keys and values.

我在想这是否可以使用匿名类型发生,或者我可以采用一种配置来实现我的目标吗?

I'm thinking if this can happen using anonymous types, or is there a configuration I can take to accomplish my goal?

谢谢.

推荐答案

好的,假设您拥有:

[DataContract]
public class MyObject
{
    [DataMember(Name = "extra_data")]
    public Dictionary<string, string> MyDictionary { get; set; } 

}

然后您可以在UseSimpleDictionaryFormat设置为true的情况下使用DataContractJsonSerializerSettings,如下所示:

Then you can use DataContractJsonSerializerSettings with UseSimpleDictionaryFormat set to true, something like this:

    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());
    }

这篇关于使用DataContractJsonSerializer将Dictionary序列化为JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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