6

My web API is sending this JSON.

{   "data":[  
  {  
     "cat_id":"1",
     "category":"Clothing",
     "img_url":"sampleUrl.com"
  },
  {  
     "cat_id":"2",
     "category":"Electronic Shop",
     "img_url":"sampleUrl.com"
  },
  {  
     "cat_id":"3",
     "category":"Grocery",
     "img_url":"sampleUrl.com"
  },
  {  
     "cat_id":"4",
     "category":"Hardware",
     "img_url":"sampleUrl.com"
  }

  ]}

I tried to deserialize this JSON using below c# code

var result = JsonConvert.DeserializeObject<List<AllCategories>>(content);

but it throws an exception.

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[EzyCity.AllCategories]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

AllCategories class

 public class AllCategories
{
    private string cat_id;
    private string category;
    private string img_url;

    public string Cat_Id
    {
        get { return cat_id; }
        set { cat_id = value; }
    }

    public string Category
    {
        get { return category; }
        set { category = value; }
    }

    public string Image_Url
    {
        get { return img_url; }
        set { img_url = value; }
    }
}

What should be done to deserialize this type of JSON?

udi
  • 303
  • 1
  • 6
  • 19

2 Answers2

7

Your json is a object with an array as the following:

public class ObjectData
{
   public List<AllCategories> data{get;set;}
}

Therefore you have to desirialize the Json into the object:

var result = JsonConvert.DeserializeObject<ObjectData>(content);
Old Fox
  • 8,629
  • 4
  • 34
  • 52
6

you need something like this

public class Datum
{
    public string cat_id { get; set; }
    public string category { get; set; }
    public string img_url { get; set; }
}

public class RootObject
{
    public List<Datum> data { get; set; }
}

then use

var result = JsonConvert.DeserializeObject<RootObject>(content);

to de-serialize

Tawfik Khalifeh
  • 939
  • 6
  • 21