我尝试使用一个 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) 会生成正确的客户数量,但所有数据均为空。
执行客户列表(如下)的操作会导致“无法反序列化当前 JSON 数组”异常
public class CustomerList
{
public List<Customer> customer { get; set; }
}
思潮?
您可以创建一个新模型来反序列化您的 JSON 客户 Json
:
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
对于不想创建任何模型的用户,请使用以下代码:
var result = JsonConvert.DeserializeObject<
List<Dictionary<string,
Dictionary<string, string>>>>(content);
注意:这不适用于您的 JSON 字符串。这不是任何 JSON 结构的通用解决方案。
使用接受的答案,您必须使用 Customers[i].customer
访问每条记录,并且您需要一个额外的 CustomerJson
类,这有点烦人。如果不想这样做,可以使用以下内容:
public class CustomerList
{
[JsonConverter(typeof(MyListConverter))]
public List<Customer> customer { get; set; }
}
请注意,我使用的是列表
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();
}