使用DataContractJsonSerializer序列化复杂字典

本文关键字:字典 复杂 序列化 DataContractJsonSerializer 使用 | 更新日期: 2023-09-27 18:29:20

使用.NET 4.5版本的DataContractJsonSerializer,并借助DataContractJson SerializerSettings。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

使用DataContractJsonSerializer序列化复杂字典

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

请参阅MSDN条目