简体   繁体   中英

Deserializing nested JSON arrays using RestSharp

I'm trying to deserialize the following JSON response using RestSharp. I have tried various model structures to extract the data to no avail. I keep getting tripped up on the nested arrays.

I do not have control over the service, so I can't change the format.

JSON Format:

[
    {
        "results": 19,
        "statuscode": 200,
    },
    [
        {
            "id": 24,
            "name": "bob"
        },
        {
            "id": 82,
            "name": "alice"
        }
    ]
]

Using this model, I've been able to pull the data from the first object, but that's all. I'm not sure how exactly to read through the array that comes after the object.

public class Info
{
    public int results { get; set; }
    public int statuscode { get; set; }
}

Example deseralization:

var deserializer = new JsonDeserializer();
var wat = deserializer.Deserialize<List<List<Info>>>(response);

Am I just completely missing something here or are my only options to write a custom deserializer and/or use something like JSON.NET?

The problem is that your JSON array is exceptionally polymorphic: its first element is an object, and its second element is an array of objects. A more natural way to represent this would have been as a JSON object with two named properties -- but that's not what you have been given. Deserializing this directly to ac# POCO with two named properties in a single step with any serializer is going to be tricky since the JSON data model is quite different than your desired data model. Instead, it may be easiest to deserialize to an intermediate representation and convert. Luckily RestSharp has appropriate intermediate classes JsonObject and JsonArray .

Thus, if you want to deserialize to the following classes:

public class Info
{
    public int results { get; set; }
    public int statuscode { get; set; }
}

public class IdAndName
{
    public int id { get; set; }
    public string name { get; set; }
}

public class ResponseContent
{
    public Info Info { get; set; }
    public List<IdAndName> Data { get; set; }
}

You can do:

        var array = (JsonArray)SimpleJson.DeserializeObject(response.Content);
        var responseContent = (array == null ? (ResponseContent)null : new ResponseContent()
        {
            Info = array.OfType<JsonObject>().Select(o => SimpleJson.DeserializeObject<Info>(o.ToString())).FirstOrDefault(),
            Data = array.OfType<JsonArray>().SelectMany(a => SimpleJson.DeserializeObject<List<IdAndName>>(a.ToString())).ToList()
        });

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