我想解析一個休息API的Json響應。我可以得到很好的答覆,並創建了一些類模型。我正在使用Newtonsoft的Json.Net。Deserialise嵌套的JSON與Newtonsoft和C#
我不斷收到空值在我的迴應,我不知道如果我已經安裝我的模型正確或缺少的東西?
什麼我試圖得到的是例如,名字和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結構。
嗨傑克,我創建了一個處理Data類的父類。我現在有一些工作。問題似乎是需要映射到類的嵌套的ClientDetails對象。我也創建了這個類,但得到一個錯誤,告訴我ClientDetails需要一個JSON對象才能正確地反序列化。這可能是JArray或其他東西,但不知道如何使用它與響應? – KDee 2012-07-17 11:15:08