【问题标题】:Serialize complex dictionary with DataContractJsonSerializer使用 DataContractJsonSerializer 序列化复杂字典
【发布时间】:2013-08-28 21:11:22
【问题描述】:

使用 .NET 4.5 版本的 DataContractJsonSerializer 并在 DataContractJsonSerializerSettings.UseSimpleDictionaryFormat 的帮助下,我可以序列化字典。所以例如这本字典:

var dic = new Dictionary<string, object> 
{
  { "Level", 3 },
  { "Location", "Catacomb" }
};

将被转换成漂亮的 JSON:

{
  "Level":3,
  "Location":"Catacomb"
}

但如果我有另一个字典作为值:

var dic = new Dictionary<string, object> 
{
    { "Level", 3 },
    { "Location", new Dictionary<string, object> 
        {
            { "Name", "Catacobms" }
        }
    }
};

生成的 JSON 看起来很糟糕:

{
   "Level":3,
   "Location":[
      {
         "__type":"KeyValuePairOfstringanyType:#System.Collections.Generic",
         "key":"Name",
         "value":"Catacobms"
      }
   ]
}

有没有办法解决这个问题?

PS:我知道还有其他不错的 JSON 序列化器,但是在这种情况下我需要使用 DataContractJsonSerializer

【问题讨论】:

    标签: c# json dictionary datacontractjsonserializer


    【解决方案1】:

    尝试将序列化程序上的EmitTypeInformation 属性设置为EmitTypeInformation.Never

    MSDN Entry

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-01
      • 1970-01-01
      • 2014-08-21
      相关资源
      最近更新 更多