使用Json.net反序列化JSON对象数组
我试图使用下面的示例结构为他们返回的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)结果的正确数量的客户,但所有的数据是空的。
做一个CustomerList(下面)的结果是“无法反序列化当前的JSON数组”exception
public class CustomerList { public List<Customer> customer { get; set; } }
思考?
您可以创build一个新的模型来反序列化您的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);
希望它有帮助!
文档: 序列化和反序列化JSON
对于那些不想创build任何模型的人,请使用以下代码:
var result = JsonConvert.DeserializeObject< List<Dictionary<string, Dictionary<string, string>>>>(content);