我正在尝试从Rest API解析Json响应。我可以得到良好的响应,并创建了一些类模型。我正在使用Newtonsoft的Json.Net.
我在响应中不断得到空值,不确定我是否正确设置了我的模型,或者遗漏了什么?
例如,我试图获得的是Data\Items\AEmployee 中的Firstname和ReferenceNumber
我Json回应的一个例子是:
{
"Data": {
"Links": [
{
"Rel": "parent",
"Href": "http://Api/url/",
"Title": "Api",
}
],
"Items": [
{
"Employee": {
"ReferenceNumber": "0078952",
"EmployeeStatus": {
"Name": "Active",
"Value": 2
},
"ContactByPost": true,
"ContactByMarketingEmails": true,
"ClientDetails": [
{
"LimitedCompany": {
"Id": "809f4455-673d-df11-9849-00155d072900",
"Name": "Company"
},
"ClientCompany": {
"Id": "62494f0c-617d-412f-81a3-ca40ef80f774",
"Name": "Company 2"
},
"Code": "G67D",
"RefCode": "1271",
"Date": "/Date(1333456265000+0100)/",
"Id": "009ea227-887d-e111-96ec-000c29128cee",
"CreatedOn": "/Date(1333455954000+0100)/",
"CreatedBy": {
"Id": "5c2cb5eb-7368-e111-96eb-000c29128cee",
"Name": "System Administrator"
},
"Archived": false
}
],
"Title": {
"Name": "Mr",
"Value": 1
},
"FirstName": "Fred",
"MiddleName": null,
"LastName": "Flintstone",
"KnownAs": null,
"DateOfBirth": "/Date(315576000000+0000)/",
"Gender": {
"Name": "Male",
"Value": 1
},
"HomePhoneNumber": "55555555555",
"MobilePhoneNumber": null,
"Addresses": null,
"EmailAddresses": null,
"Id": "009ea227-887d-e111-96ec-000c29128cee",
"CreatedOn": "/Date(1333455954000+0100)/",
"CreatedBy": {
"Id": "5c2cb5eb-7368-e111-96eb-000c29128cee",
"Name": "System Administrator"
},
"Archived": false
},
"Links": [
{
"Rel": "list",
"Href": "http://Api/Addresses",
"Title": "Addresses",
"Description": "Get a list of addresses for this Employee."
}
]
}
]
}
}
我的模型设置如下所示:
public class Data
{
public Collection<Links> Links { get; set; }
public Collection<Items> Items { get; set; }
}
public class Items
{
public Employee Employee { get; set; }
}
public class Employee
{
public string ReferenceNumber { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public string Id { get; set; }
}
public class Links
{
public string Rel { get; set; }
public string Href { get; set; }
public string Title { get; set; }
public string Description { get; set; }
}
在我的控制器中,我正在执行以下操作:
Data data = Newtonsoft.Json.JsonConvert.DeserializeObject<Data>(APIResponse);
当调试时,我看到的只是Items和Links,它们都为null。我真的不确定我做错了什么,也不确定我是如何做到这一点的,这样我就可以访问C#代码中的值了?如有任何帮助,我们将不胜感激。应用程序是MVC3。我看到的例子是使用简单的json结构。
若要修复此问题,请移除包装对象,这样就只剩下以下内容:{"项目":[..],"链接":[…]}
并再次尝试反序列化。
我设法解决了这个问题。正如@Jake也提到的那样,我所做的是首先创建父类来处理Data对象。我在Employee类中创建了一个ClientDetails类型的类,如下所示:
public ClientDetails clientDetails {get; set;}
这导致了一个错误,因为ClientDetails是一个数组。我将其更改为以下内容:
public List<ClientDetails> clientDetails {get; set;}
这解决了问题,现在我的整个Data对象都填充了来自API的响应。
@杰克,谢谢你的意见。。。