【问题标题】:Serialize a Dictionary as JSON object using DataContractJsonSerializer使用 DataContractJsonSerializer 将字典序列化为 JSON 对象
【发布时间】:2013-12-31 23:46:21
【问题描述】:

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

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

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

现在我需要这样的 JSON 模式

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

当然,在值是什么之前,您永远无法知道,用户将设置键和值是Dictionary

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

谢谢。

【问题讨论】:

标签: c# json serialization dictionary


【解决方案1】:

好吧,假设你有:

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

}

然后您可以使用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());
    }

【讨论】:

  • 完美而简单。谢谢。
  • 对于 Windows Phone 8,我使用了 Newtonsoft JSON 序列化程序 Nuget 包。 james.newtonking.com/json
  • 我根本没有 DataContractJsonSerializerSettings(运行 .NET 4.5),它不存在。
  • 你好,当我在代码中创建服务主机时,我在哪里可以用这个序列化器替换“普通”序列化器?
  • DataContractJsonSerializerSettings 在 .NET 4.0 中不可用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多