Israq Khan
Israq Khan

Reputation: 41

How to deserialize a JSON array with nested arrays of objects

I have a JSON string as follows and want to deserialize it:

[[{"campaignId":201410018,"programCode":"54321"}],[{"campaignId":201410018,"programCode":"54321"}]]

I have created some classes as follows:

public class Rootclass
{
    public List<JSONResponse> rootClass { get; set; }
}

public class JSONResponse
{
    public int campaignId { get; set; }
    public string programCode { get; set; }
}

I am calling this JSON.NET method to deserialize the JSON:

List<Rootclass> myDeserializedObjList = (List<Rootclass>)Newtonsoft.Json.JsonConvert.DeserializeObject(json, typeof(List<Rootclass>));

But I am getting the error below:

Cannot deserialize JSON array (i.e. [1,2,3]) into type 'JSON_Test.Rootclass'.
The deserialized type must be an array or implement a collection interface like IEnumerable, ICollection or IList.

What am I doing wrong?

Upvotes: 3

Views: 10648

Answers (1)

Brian Rogers
Brian Rogers

Reputation: 129697

Your JSON represents a List<List<JSONResponse>>, not a List<RootClass>. Try it like this:

List<List<JSONResponse>> myDeserializedObjList = 
    JsonConvert.DeserializeObject<List<List<JSONResponse>>>(json);

Fiddle: https://dotnetfiddle.net/geRLdb

Upvotes: 4

Related Questions