我正在尝试使用一个 API,该 API 将以下示例结构用于返回的 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 可以很好地处理类似以下结构的内容
{
"customer": {
["field1" : "value", etc...],
["field1" : "value", etc...],
}
}
但我不知道如何让它对提供的结构感到满意。
使用默认的 JsonConvert.DeserializeObject(content) 会得到正确数量的 Customer,但所有数据都为空。
对 CustomerList(如下)执行某些操作会导致“无法反序列化当前 JSON 数组”异常
public class CustomerList
{
public List<Customer> customer { get; set; }
}
想法?
最佳答案
您可以创建一个新模型来反序列化您的 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:
JsonConvert.DeserializeObject<List<CustomerJson>>(json);
关于c# - 使用 Json.net 反序列化 JSON 对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18192357/