与反序列化Json.net JSON对象数组 [英] Deserializing JSON Object Array with Json.net

查看:155
本文介绍了与反序列化Json.net JSON对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用使用遵循示例结构为他们返回的JSON的API

I am attempt to use an API that use the follow example structure for their returned 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将与类似如下结构工作的伟大

JSON.net would work great with something like the following structure

{
    "customer": {
        ["field1" : "value", etc...],
        ["field1" : "value", etc...],
    }
}

但我无法弄清楚如何得到它的快乐与所提供的结构。

But I can not figure out how to get it to be happy with the provided structure.

使用默认JsonConvert.DeserializeObject(内容)的结果客户的正确数目,但所有的数据为空。

Using the default JsonConvert.DeserializeObject(content) results the correct number of Customer but all of the data is null.

做东西CustomerList(下图)的结果是无法反序列化当前的JSON数组异常

Doing something a CustomerList (below) results in a "Cannot deserialize the current JSON array" exception

public class CustomerList
{
    public List<Customer> customer { get; set; }
}

思考?

推荐答案

您可以创建一个新的模型来反序列化您的JSON CustomerJson

You can create a new model to Deserialize your 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:

And you can deserialize your json easily :

JsonConvert.DeserializeObject<List<CustomerJson>>(json);

希望它帮助!

文档: 序列化和反序列化JSON

这篇关于与反序列化Json.net JSON对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆