Consider the following scenario:
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);
This deserializes into a Dictionary<string, object>
, with for key "0" an array with 2 integers. Great!
Now let's try this:
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);
Now, deserialized["0"]
is a JObject. Using a JsonSerializerSettings
argument to DeserializeObject with TypeNameHandling = TypeNameHandling.All
solves this.
Now, in my actual scenario, there's another list around the dictionary object, and this is where further deserialization seems possible:
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);
Here, deserialized[0]
is a JObject
, which I cannot seem to convince json.net to deserialize further into another Dictionary<string, object>
. Is this possible?