考虑以下情况:
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>
。这可能吗?