How do I use JSON.NET to deserialize into nested/recursive Dictionary and List?

If you just want a generic method that can handle any arbitrary JSON and convert it into a nested structure of regular .NET types (primitives, Lists and Dictionaries), you can use JSON.Net’s LINQ-to-JSON API to do it:

using System.Linq;
using Newtonsoft.Json.Linq;

public static class JsonHelper
{
    public static object Deserialize(string json)
    {
        return ToObject(JToken.Parse(json));
    }

    public static object ToObject(JToken token)
    {
        switch (token.Type)
        {
            case JTokenType.Object:
                return token.Children<JProperty>()
                            .ToDictionary(prop => prop.Name,
                                          prop => ToObject(prop.Value));

            case JTokenType.Array:
                return token.Select(ToObject).ToList();

            default:
                return ((JValue)token).Value;
        }
    }
}

You can call the method as shown below. obj will either contain a Dictionary<string, object>, List<object>, or primitive depending on what JSON you started with.

object obj = JsonHelper.Deserialize(jsonString);

Leave a Comment