我正在使用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类对象?
最佳答案
通过Persons
而不是Deserialize<T>
persons = serializer.Deserialize<Persons>(response.Body);
重命名属性
public PersonInfo[] infos;
到
public PersonInfo[] persons;
另外,我建议您使用auto属性。即
public PersonInfo[] persons{get;set;}