Home > Back-end >  Deserialising a dictionary of dictionaries into a Dictionary<string, object>
Deserialising a dictionary of dictionaries into a Dictionary<string, object>

Time:01-01

I have serialized a dictionary named state1 to json in C# with this code:

string json = JsonConvert.SerializeObject(state1, Formatting.Indented);

The value of this dictionary is another dictionary and when I deserialize the json file back to dictionary the values are not deserialised as dictionaries (I cannot cast the object back to a Dictionary<string, object>):

var values = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);

How can I deserialize the json correctly?

CodePudding user response:

If you want the original shape back, you need to use the original type when deserialising.

If, as it seems from your comment, that it's a dictionary of dictionaries of object, you'd need to use this when deserialising:

var values = JsonConvert
    .DeserializeObject<Dictionary<string, Dictionary<string, object>>>(json);

If you need to treat this as a Dictionary<string, object> while still ensuring that the inner dictionary contents are deserialised as dictionaries (and not JObject), you can "cast" it in this way (as per this answer):

var values = JsonConvert
    .DeserializeObject<Dictionary<string, Dictionary<string, object>>>(json)
    .ToDictionary(x => x.Key, x => (object)x.Value);
  • Related