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

This is an example of 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 the Json.NET library. You can download 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