4

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 ?

theGeekster
  • 6,081
  • 12
  • 35
  • 47
  • 1
    Here is a handy tool - simply paste in some example JSON, and it will generate a compatible C# object: http://json2csharp.com/ – Steve Jan 03 '14 at 16:27

1 Answers1

5

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;}
Satpal
  • 132,252
  • 13
  • 159
  • 168
  • Passed Persons instead of Vendors (this was a typo). Renamed infos to persons and that solved my problem. Thanks a lot. – theGeekster Jan 03 '14 at 16:18