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);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…