JSON & DataTable in asp.net / c#

Before start you need to convert your json data to c# class. You can achieve this by using online tools like : http://json2csharp.com/


  1. Go to : http://json2csharp.com/
  2. Paste your Json data into box and click Generate Button.
  3. Copy the code generated and create Class file in your asp.net solution.


After finish convert json data to c# class, Copy the code below.

Example JSON Data

1:   {    
2:     "name":"apicode",   
3:     "email":   
4:     [   
5:        "apicode@gmail.com","apicode@gmail.com"   
6:     ],   
7:     "websites":    
8:     {   
9:        "home_page":"http:\/\/apicode.blogspot.com",   
10:        "blog":"http:\/\/apicode.blogspot.com"   
11:     }   
12:   }   


JSON Class after converted

1:   public class Websites   
2:   {   
3:    public string home_page { get; set; }   
4:    public string blog { get; set; }   
5:   }   
6:   public class RootObject   
7:   {   
8:    public string name { get; set; }   
9:    public List<string> email { get; set; }   
10:   public Websites websites { get; set; }   
11:  }   

C# Code 

1:     public DataTable ParseResponse(WebResponse response)   
2:     {   
3:      DataTable table = new DataTable();   
4:      table.Columns.Add("name", typeof(string));   
5:      table.Columns.Add("home_page", typeof(string));   
6:      table.Columns.Add("blog", typeof(string));   
7:      table.Columns.Add("email", typeof(string));   
8:      using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))   
9:      {   
10:       var joResponse = JObject.Parse(reader.ReadToEnd());   
11:       var rootObj = JsonConvert.DeserializeObject<RootObject>(joResponse.ToString());       
12:       //add new row   
13:       DataRow row = table.NewRow();   
14:       //class string   
15:       row["name"] = rootObj.name;   
16:       //class List<string>   
17:       row["email"] = String.Join("|", rootObj.email);   
18:       //class website   
19:       row["blog"] = rootObj.websites.blog;   
20:       row["home_page"] = rootObj.websites.home_page;   
21:       table.Rows.Add(row);    
22:      }   
23:      return table;   
24:     }   


Note : the example above using JSon.NET library. You can donwload the library here http://www.newtonsoft.com/json

Popular posts from this blog

How to create zip file to download in JSP- Servlet

How to create DataGrid or GridView in JSP - Servlet

Pinging in ASP.NET Example