c# - 使用 Json.net 反序列化 JSON 对象数组

标签 c# json.net

我正在尝试使用一个 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);

文档:Serializing and Deserializing JSON

关于c# - 使用 Json.net 反序列化 JSON 对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18192357/

相关文章:

c# - SQLSERVER和dot.net之间的消息限制错误

c# - 是否可以在 C# 中使用 iTextSharp 修改 PDF 中的专色名称?

c# - 引用自动创建的对象

c# - 在属性名称前加上一些字符 - JSON 序列化

c# - 在 JSON.NET 中反序列化的转换接口(interface)

c# - 从 JObject 中提取值

c# - 如果我向 AddControllersWithViews() 添加扩展,它是否也适用于 AddRazorPages()

c# - 获取用户上次访问时间

c# - 针对只有一个类实现所述接口(interface)的接口(interface)进行编程

javascript - @符号打破 Angular 表达