How to map JSON response to custom class object

theGeekster picture theGeekster · Jan 3, 2014 · Viewed 10.4k times · Source

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 ?

Answer

Satpal picture Satpal · Jan 3, 2014

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;}