3

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?

0

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

How can a deserialize below JSON string. string json = @"[[{""campaignId"":201410018,""programCode"":""54321""},{""reason"":201410018,""about"":""54321""}],[{""campaignId"":201410019,""programCode"":""54322""},{""reason"":201410018,""about"":""54321""}]]";
There are several possible solutions. The quick-and-dirty way is simply to add the reason and about properties to your JSONResponse object. See fiddle here. If you want separate classes for the objects containing campaignId versus reason, then you will need to use a JsonConverter. A third possibility is to deserialize to a dynamic or a JToken instead of using strongly-typed classes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.