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

ぃ、小莉子 提交于 2020-01-13 11:28:32

问题


I'm getting my data from a website which returns a .json format that is quite unfamiliar to me. I've been looking for the solution for a couple of hours, and I must be using the terminology.

The json is formatted something like this:

[
{
    "Foo": {
        "name": "Foo",      
        "size": {
            "human": "832.73kB",
            "bytes": 852718
        },
        "date": {
            "human": "September 18, 2017",
            "epoch": 1505776741
        },
    }
},
{
    "bar": {
        "name": "bar",
        "size": {
            "human": "4.02MB",
            "bytes": 4212456
        },
        "date": {
            "human": "September 18, 2017",
            "epoch": 1505776741
        }
    }
}]

I'm using Newtonsoft's JSON.NET, and I can't seem to be able to create a data structure that would allow me to deserialize it, since it's the array of classes with different names. Specifically the property names "Foo" and "bar" could differ at runtime. Property names elsewhere in the JSON hierarchy are known.


回答1:


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.



来源:https://stackoverflow.com/questions/46355071/deserializing-a-list-of-objects-with-different-names-in-json-net

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