反复地反序列化对象'与json.net

时间:2014-01-20 10:33:17

标签: c# json json.net json-deserialization

考虑以下情况:

var toSerialize = new Dictionary<string, object> {
  { "0", new[] { 1, 2 } } 
};
string serialized =  JsonConvert.SerializeObject(toSerialize);
// serialized == {"0":[1,2]}
var deserialized = JsonConvert.DeserializeObject<Dictionary<string, object>>(serialized);

这反序列化为Dictionary<string, object>,键为“0”,数组为2个整数。太好了!

现在让我们试试这个:

var toSerialize = new Dictionary<string, object> {
    { "0", new Dictionary<string, object> { {  "0.0", new[] { 1, 2 } } } }
};
string serialized = JsonConvert.SerializeObject(toSerialize);
// serialized == {"0":{"0.0":[1,2]}}
var deserialized = JsonConvert.DeserializeObject<Dictionary<string, object>>(serialized);

现在,deserialized["0"]是一个JObject。使用带有JsonSerializerSettings的DeserializeObject的TypeNameHandling = TypeNameHandling.All参数解决了这个问题。

现在,在我的实际场景中,字典对象周围还有另一个列表,这是进一步反序列化的地方:

var toSerialize = new List<Dictionary<string, object>> { new Dictionary<string, object> {
  { "0", new Dictionary<string, object> { {  "0.0", new[] { 1, 2 } } } }
} };
string serialized = JsonConvert.SerializeObject(toSerialize);
// serialized == [{"0":{"0.0":[1,2]}}]
var deserialized = JsonConvert.DeserializeObject<IList<Dictionary<string, object>>>(serialized, _jsonSettings);

在这里,deserialized[0]JObject,我似乎无法说服json.net进一步反序列化为另一个Dictionary<string, object>。这可能吗?

0 个答案:

没有答案