Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Deserialize JSON(multi level) in C#

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?

like image 260
udi Avatar asked Jul 28 '15 07:07

udi


1 Answers

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);
like image 183
Old Fox Avatar answered Sep 22 '22 12:09

Old Fox