How to map JSON response to custom class object

佐手、 提交于 2019-12-30 05:11:13

问题


I am calling an API in C# using unirest.io. I get following JSON response (as response.Body).

{
    "persons": [{
        "id": "a010",
        "name": "Joe",
        "subjects": [
            "Math",
            "English"
        ]
    },
    {
        "id": "b020",
        "name": "Jill",
        "subjects": [
            "Science",
            "Arts"
        ]
    }]
}

I tried to map this to my custom class object as follows.

HttpRequest request = Unirest.get(API_V1_URL).header("accept", "application/json");
HttpResponse<string> response = request.asString();
var serializer = new JavaScriptSerializer();
persons = serializer.Deserialize<Persons>(response.Body);

But it always pass through by setting persons.infos = NULL;

My Custom Class

public class Persons
{
    public PersonInfo[] infos;
}

public class PersonInfo
{
    public string id;
    public string name;
    public string[] subjects;
}

Please assist me how can I correctly map such JSON to my .Net class objects ?


回答1:


Pass Persons in Deserialize<T> instead of Vendors

persons = serializer.Deserialize<Persons>(response.Body);

Rename property

public PersonInfo[] infos;

To

public PersonInfo[] persons;

Additionally, I would recommend you to use Auto-properties. i.e.

public PersonInfo[] persons{get;set;}


来源:https://stackoverflow.com/questions/20907775/how-to-map-json-response-to-custom-class-object

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