Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserializing an array of objects with Json.Net

Tags:

json

c#

json.net

The received data is like this:

enter image description here

Inside each item, there is an object, customer, I have an identical class for that. How can I convert them using Json.net?

I have tried the followings:

var data = JsonConvert.DeserializeObject<List<customer>>(val);

and adding another class:

public class customerJson
{
    public Customer customer{ get; set; }
}

And trying to deserialize it:

var data = JsonConvert.DeserializeObject<List<customerJson>>(val);

With both of them I get an exception:

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[customer]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. Path 'rows', line 1, position 8.

Data:

{"rows":[{"id":"232333","name":"nam"},{"id":"3434444","name":"2ndName"}]}
like image 773
Akbari Avatar asked Jul 02 '15 06:07

Akbari


2 Answers

If I read your json data structure correctly you would want this:

public class Root
{
    public List<Customer> rows { get; set; }
}

and

var data = JsonConvert.DeserializeObject<Root>(val);

Tested code:

void Main()
{
    var test = JsonConvert.DeserializeObject<Root>("{\"rows\":[{\"id\":\"232333\",\"name\":\"nam\"},{\"id\":\"3434444\",\"name\":\"2ndName\"}]}");

    Console.WriteLine(test.rows[0].id); // prints 232333
}

public class Customer
{
    public int id { get; set; }
}

public class Root
{
    public List<Customer> rows { get; set; }
}
like image 173
asgerhallas Avatar answered Oct 12 '22 22:10

asgerhallas


Just in case anyone is still having issues. This worked out for me:

If the Json looks something like this:

"result": [
        {
            "firstname": "John",
            "lastname": "Doe",

        }, 
        {
            "firstname": "Max",
            "lastname": "Mustermann",
        }
    ]

ResultList.cs

public class ResultList {

  [JsonProperty("result")]
  public List<ResultObj> ResultObj { get; set }

}

ResultObj.cs

public class ResultObj {

  [JsonProperty("firstname")]
  public string FirstName { get; set; }

  [JsonProperty("lastname")]
  public string LastName{ get; set; }

}

And finally:

using Newtonsoft.Json;

var resultList = JsonConvert.DeserializeObject<ResultList>(jsonString);
like image 38
Bumber Avatar answered Oct 12 '22 23:10

Bumber