我使用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类对象?
答案 0 :(得分:3)
在Persons
而不是Deserialize<T>
Vendors
persons = serializer.Deserialize<Persons>(response.Body);
重命名属性
public PersonInfo[] infos;
要
public PersonInfo[] persons;
此外,我建议您使用自动属性。即。
public PersonInfo[] persons{get;set;}