2

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?

Frank Razenberg
  • 511
  • 4
  • 17
  • maybe try making a simple POCO class with your data structur to which you can deserialize in.. That way JSON.Net might be able to handle it better.. Just a thought ofcourse.. – Yves Schelpe Jan 20 '14 at 10:40
  • Hm, the solution in the possible duplicate works for this case. I simplified my actual case, where there's another list around the dictionary, and then the suggested solution does not seem to do the trick. I'll quickly update. – Frank Razenberg Jan 20 '14 at 10:42
  • 1
    Are you wedded to `Dictionary`? JObject/JToken are a perfectly adequate substitute. JObject even implements IDictionary. – Anton Tykhyy Jan 20 '14 at 11:33
  • Wow, how did I miss that. Non-issue indeed, thanks. – Frank Razenberg Jan 20 '14 at 12:38

0 Answers0