【发布时间】: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