Removing the deserialization of an array of JSON objects using Json.net

I am trying to use an API that uses the following example structure for json returned

[ { "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 does a great job with something like the following structure

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

But I can’t understand how to make him be happy with the structure provided.

Using the standard JsonConvert.DeserializeObject (content) results in the correct number of clients, but all data is zero.

Performing something from the list of clients (below) results in the exception "Unable to deserialize the current JSON array"

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

Thoughts?

+84
Aug 12 '13 at 16:45
source share
2 answers

You can create a new model for Json CustomerJson deserialization:

 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 easily deserialize your json:

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

Hope this helps!

Documentation: Serializing and Deserializing JSON

+132
Aug 12 '13 at 16:56
source share

For those who do not want to create any models, use the following code:

 var result = JsonConvert.DeserializeObject< List<Dictionary<string, Dictionary<string, string>>>>(content); 
+39
Jun 30 '14 at 7:47
source share



All Articles