Deserializing nested JSON arrays using RestSharp

白昼怎懂夜的黑 提交于 2020-01-05 23:46:54

问题


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?


回答1:


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 a c# 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()
        });


来源:https://stackoverflow.com/questions/29208260/deserializing-nested-json-arrays-using-restsharp

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