如何将JSON响应映射到自定义类对象

时间:2014-01-03 16:03:44

标签: c# json jsonserializer unirest

我使用unirest.io在C#中调用API。我得到了JSON响应(作为 response.Body )。

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

我尝试将此映射到我的自定义类对象,如下所示。

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

但它总是通过设置 persons.infos = NULL ;

来传递

我的自定义类

public class Persons
{
    public PersonInfo[] infos;
}

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

请帮助我如何正确地将这样的JSON映射到我的.Net类对象?

1 个答案:

答案 0 :(得分:3)

Persons而不是Deserialize<T>

中传递Vendors
persons = serializer.Deserialize<Persons>(response.Body);

重命名属性

public PersonInfo[] infos;

public PersonInfo[] persons;

此外,我建议您使用自动属性。即。

public PersonInfo[] persons{get;set;}