简体   繁体   中英

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

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.

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 ac# 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM