Deserializing a list of objects with different names in JSON.NET

▼魔方 西西 提交于 2019-12-05 13:36:28

Assuming that only the names "Foo" and "Bar" are unknown at compile time, you can deserialize that JSON into a List<Dictionary<string, RootObject>>, where RootObject is a c# model I generated automatically using http://json2csharp.com/ from the JSON for the value of "Foo".

Models:

public class Size
{
    public string human { get; set; }
    public int bytes { get; set; }
}

public class Date
{
    public string human { get; set; }
    public int epoch { get; set; }
}

public class RootObject
{
    public string name { get; set; }
    public Size size { get; set; }
    public Date date { get; set; }
}

Deserialization code:

var list = JsonConvert.DeserializeObject<List<Dictionary<string, RootObject>>>(jsonString);

Notes:

  • The outermost type must be an enumerable such List<T> since the outermost JSON container is an array -- a comma-separated sequence of values surrounded by [ and ]. See Serialization Guide: IEnumerable, Lists, and Arrays.

  • When a JSON object can have arbitrary property names but a fixed schema for property values, it can be deserialized to a Dictionary<string, T> for an appropriate T. See Deserialize a Dictionary.

  • Possibly bytes and epoch should be of type long.

Working .Net fiddle.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!