Saturday, 3 October 2015

How to read JSON Data and convert to DataTable - asp.net / c#

Leave a Comment
This is example how to read JSON Data using c# code.

First before you start coding, please read this post on how to convert json data to c# class.

How to convert JSON data to Class - C#

After finish convert json data to c# class, write this code to read your json data.

Example JSON Data

  {   
      "name":"swengineercode",  
      "email":  
      [  
           "swengineercode@gmail.com","swengineercode@gmail.com"  
      ],  
      "websites":   
      {  
           "home_page":"http:\/\/swengineercode.blogspot.com",  
           "blog":"http:\/\/swengineercode.blogspot.com"  
      }  
 }  


JSON Class after converted

  public class Websites  
 {  
   public string home_page { get; set; }  
   public string blog { get; set; }  
 }  
 public class RootObject  
 {  
   public string name { get; set; }  
   public List<string> email { get; set; }  
   public Websites websites { get; set; }  
 }  

C# Code 

   public DataTable ParseResponse(WebResponse response)  
     {  
       DataTable table = new DataTable();  
       table.Columns.Add("name", typeof(string));  
       table.Columns.Add("home_page", typeof(string));  
       table.Columns.Add("blog", typeof(string));  
       table.Columns.Add("email", typeof(string));  
       using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))  
       {  
         var joResponse = JObject.Parse(reader.ReadToEnd());  
         var rootObj = JsonConvert.DeserializeObject<RootObject>(joResponse.ToString());         
         //add new row  
         DataRow row = table.NewRow();  
         //class string  
         row["name"] = rootObj.name;  
         //class List<string>  
         row["email"] = String.Join("|", rootObj.email);  
         //class website  
         row["blog"] = rootObj.websites.blog;  
         row["home_page"] = rootObj.websites.home_page;  
         table.Rows.Add(row);    
       }  
       return table;  
     }  


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


By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)

0 comments:

Post a Comment

Subscribe to our newsletter to get the latest updates to your inbox.

Your email address is safe with us!




Founder of developersnote.com, love programming and help others people. Work as Software Developer. Graduated from UiTM and continue study in Software Engineering at UTMSpace. Follow him on Twitter , or Facebook or .



Powered by Blogger.