Deserialize JSON recursively to IDictionary<string,object>

c#, json, json.net

Solution

When Deserializing your complex objects using Json, you need to add a JsonSerializer Settings as a parameter. This will ensure that all of the inner types get deserialized properly.

    private JsonSerializerSettings _jsonSettings = new JsonSerializerSettings
    {
        TypeNameHandling = TypeNameHandling.All,
        TypeNameAssemblyFormat = FormatterAssemblyStyle.Full
    };

When Serializing your object, you can use the SerializerSettings:

    string json= JsonConvert.SerializeObject(myObject, _jsonSettings)

Then when you are deserializing, use:

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

Also, when you serialize, add the JsonSerializerSettings to your SerializeObject(object, settings)

Edit: You can also change the TypeNameHandling and TypeNameAssemblyFormat if you need to. I have them set at 'All' and 'Full' respectively to ensure that my complex objects get serialized and deserialized properly without doubt, but intellisense provides you with other alternatives

Problem

I'm trying to convert some older work to use Newtonsoft JSON.NET. The default handling using the `System.Web.Script.Serialization.JavaScriptSerializer.Deserialize` method (e.g. if no target type is specified) is to return a `Dictionary<string,object>` for inner objects. This is actually a really useful basic type for JSON since it also happens to be the underlying type used by `ExpandoObjects` and is the most sensible internal implementation for dynamic types. If I specify this type, e.g.: ``` var dict = JsonConvert.DeserializeObject<Dictionary<string,object>>(json); ``` JSON.NET will deserialize the outermost object structure correctly, but it returns a `JObject` type for any inner structures. What I really need is for the same outer structure to be used for any inner object-type structures. Is there a way to specify a type to be used for inner objects, and not just the outermost type returned?

Original source

Related problems