使用Json.net反序列化JSON对象数组我试图使用一个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数,但所有数据都为null。在CustomerList(下面)执行某些操作会导致“无法反序列化当前JSON数组”异常public class CustomerList{
public List<Customer> customer { get; set; }}思考?
3 回答
慕村225694
TA贡献1880条经验 获得超4个赞
您可以创建一个新模型来反序列化您的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);
希望能帮助到你 !
慕姐4208626
TA贡献1852条经验 获得超7个赞
使用已接受的答案,你必须使用Customers[i].customer
,访问每个记录,你需要一个额外的CustomerJson
类,这有点烦人。如果您不想这样做,可以使用以下内容:
public class CustomerList{ [JsonConverter(typeof(MyListConverter))] public List<Customer> customer { get; set; }}
请注意,我使用的是a List<>
,而不是数组。现在创建以下类:
class MyListConverter : JsonConverter{ public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var token = JToken.Load(reader); var list = Activator.CreateInstance(objectType) as System.Collections.IList; var itemType = objectType.GenericTypeArguments[0]; foreach (var child in token.Values()) { var childToken = child.Children().First(); var newObject = Activator.CreateInstance(itemType); serializer.Populate(childToken.CreateReader(), newObject); list.Add(newObject); } return list; } public override bool CanConvert(Type objectType) { return objectType.IsGenericType && (objectType.GetGenericTypeDefinition() == typeof(List<>)); } public override bool CanWrite => false; public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) => throw new NotImplementedException();}
收到一只叮咚
TA贡献1821条经验 获得超4个赞
对于那些不想创建任何模型的人,请使用以下代码:
var result = JsonConvert.DeserializeObject< List<Dictionary<string, Dictionary<string, string>>>>(content);
- 3 回答
- 0 关注
- 1222 浏览
添加回答
举报
0/150
提交
取消