我尝试使用对以下返回的json使用以下示例结构的API
[ { "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,但是所有数据均为null。
做一个CustomerList(如下)会导致“无法反序列化当前JSON数组”异常
public class CustomerList { public List<Customer> customer { get; set; } }
有什么想法吗?
您可以创建一个新模型来反序列化您的Json CustomerJson:
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);
希望能帮助到你 !
文档: 序列化和反序列化JSON