1

I know there are lots of questions on how to do this...

I have a pretty complex JSON returned from an API and I am trying to work my way through it. I simplified the JSON answer so it holds one of the immanent problems.

The simplified JSON answer

{"data":[{"type":"task","id":"10118"},{"type":"task","id":"10004"}]}

My class to be used for the deserialisation

namespace TestJsonDeserializeApp
{
    class jsonTask
    {
        public List<Data> data { get; set; }
        public class Data
        {

            public string id { get; set; }
            public string type { get; set; }
        }
    }
}

How I want to do the deserialisation

List<jsonTask> test = JsonConvert.DeserializeObject<List<jsonTask>>(strJSON);

and finally the error message I am getting

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[TestJsonDeserializeApp.jsonTask]' 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 'data', line 1, position 8.

Can one of you tell me how I have to write the jsonTask class to fit the structure of the JSON input?

TomGeo
  • 1,213
  • 2
  • 12
  • 24
  • 2
    Do `JsonConvert.DeserializeObject(strJSON);`. You don't have a json array but an object. – Ackdari Oct 15 '20 at 12:25
  • 1
    Have a look at [Load JSON text into class object in c#](https://stackoverflow.com/a/48023576/542251) – Liam Oct 15 '20 at 12:27

2 Answers2

3

Copy your JSON. Open Visual studio. Create new C# class file. Now Select below menu option:
Edit > Paste Special > Paste JSON as classes
This will create a class as below

public class Rootobject
{
    public Datum[] data { get; set; }
}

public class Datum
{
    public string type { get; set; }
    public string id { get; set; }
}

Now change RootObject to jsonTask and deserialise as below

jsonTask test = JsonConvert.DeserializeObject<jsonTask>(strJSON);
as-if-i-code
  • 2,103
  • 1
  • 10
  • 19
0

With your code you are casting the strJSON to List with a list. You need to remove the outer list since jsonTask alreadyhas the public List data { get; set; }

Try:

jsonTask test = JsonConvert.DeserializeObject(strJSON);