C# – Deserializing JSON Object Array with Json.net

cjson.net

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 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.

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

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

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

Thoughts?

Best Answer

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; }

        ...
    }

And you can deserialize your JSON easily:

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

Documentation: Serializing and Deserializing JSON