How to map a JSON response to a custom class object

I am calling the API in C # using unirest.io . I get a JSON response (like response.Body).

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

I tried to match this with 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 goes through setting person.infos = NULL;

My custom class

public class Persons
{
    public PersonInfo[] infos;
}

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

Help me how to properly match such JSON with my .Net class objects?

+4
source share
1 answer

Skip Personsin Deserialize<T>insteadVendors

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

Rename Property

public PersonInfo[] infos;

For

public PersonInfo[] persons;

In addition, I would recommend that you use Auto Properties. i.e.

public PersonInfo[] persons{get;set;}
+3
source

All Articles