問題描述
我正在嘗試使用一個 API,該 API 使用以下示例結(jié)構(gòu)來返回其返回的 json
I am attempt to use an API that use the follow example structure for their returned json
[
{
"customer":{
"first_name":"Test",
"last_name":"Account",
"email":"test1@example.com",
"organization":"",
"reference":null,
"id":3545134,
"created_at":"2013-08-06T15:51:15-04:00",
"updated_at":"2013-08-06T15:51:15-04:00",
"address":"",
"address_2":"",
"city":"",
"state":"",
"zip":"",
"country":"",
"phone":""
}
},
{
"customer":{
"first_name":"Test",
"last_name":"Account2",
"email":"test2@example.com",
"organization":"",
"reference":null,
"id":3570462,
"created_at":"2013-08-12T11:54:58-04:00",
"updated_at":"2013-08-12T11:54:58-04:00",
"address":"",
"address_2":"",
"city":"",
"state":"",
"zip":"",
"country":"",
"phone":""
}
}
]
JSON.net 可以很好地使用類似以下結(jié)構(gòu)的東西
JSON.net would work great with something like the following structure
{
"customer": {
["field1" : "value", etc...],
["field1" : "value", etc...],
}
}
但我不知道如何讓它對提供的結(jié)構(gòu)感到滿意.
But I can not figure out how to get it to be happy with the provided structure.
使用默認的 JsonConvert.DeserializeObject(content) 得到正確數(shù)量的客戶,但所有數(shù)據(jù)為空.
Using the default JsonConvert.DeserializeObject(content) results the correct number of Customer but all of the data is null.
對 CustomerList(如下)執(zhí)行操作會導(dǎo)致無法反序列化當前 JSON 數(shù)組"異常
Doing something a CustomerList (below) results in a "Cannot deserialize the current JSON array" exception
public class CustomerList
{
public List<Customer> customer { get; set; }
}
想法?
推薦答案
您可以創(chuàng)建一個新模型來反序列化您的 JSON CustomerJson
:
You can create a new model to Deserialize your JSON CustomerJson
:
public class CustomerJson
{
[JsonProperty("customer")]
public Customer Customer { get; set; }
}
public class Customer
{
[JsonProperty("first_name")]
public string Firstname { get; set; }
[JsonProperty("last_name")]
public string Lastname { get; set; }
...
}
您可以輕松地反序列化您的 JSON:
And you can deserialize your JSON easily:
JsonConvert.DeserializeObject<List<CustomerJson>>(json);
文檔:序列化和反序列化 JSON
這篇關(guān)于使用 Json.net 反序列化 JSON 對象數(shù)組的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!