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

前端 未结 5 971
-上瘾入骨i
-上瘾入骨i 2020-11-22 13:13

I need to deserialize a complex JSON blob into standard .NET containers for use in code that is not aware of JSON. It expects things to be in standard .NET

5条回答
  •  庸人自扰
    2020-11-22 13:38

    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));
        }
    
        private static object ToObject(JToken token)
        {
            switch (token.Type)
            {
                case JTokenType.Object:
                    return token.Children()
                                .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, List, or primitive depending on what JSON you started with.

    object obj = JsonHelper.Deserialize(jsonString);
    

    提交回复
    热议问题