Convert DataTable to Json

The article explains how to convert datatable to json using Json.Net DLL.

The JSON(JavaScript Object Notation) format is often used for serializing and transmitting structured data over a network connection. JSON is used primarily to transmit data between a server and web application, serving as an alternative to XML.
It is easy for humans to read and write. It is easy for machines to parse and generate.JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, etc.
These properties make JSON an ideal data-interchange language. Because of that JSON has become a popular format for data interchange in Ajax based applications.
In short JSON, is a syntax for storing and exchanging data. JSON is an easier-to-use alternative to XML.

Please download the json newton soft dll from Nuget.org or simply download the dll from the attached zip file below.

Newtonsoft.Json

Import Newtonsoft.Json namespace.

using Newtonsoft.Json;

Add below method in the default page.

public DataTable getData()
{
DataTable dt = new DataTable();
dt.Columns.Add("Name", typeof(Int32));
dt.Columns.Add("Gender", typeof(string));
dt.Columns.Add("Department", typeof(string));
dt.Columns.Add("City", typeof(string));
dt.Rows.Add(1, "Kiruba", "Male", "Chennai");
dt.Rows.Add(2, "Geetha", "Female", "Udumalpet");
dt.Rows.Add(3, "Menaka", "Female", "Karur");
dt.Rows.Add(4, "Ramya", "Female", "Namakkal");
dt.Rows.Add(5, "Arun", "Male", "Namakkal");
dt.Rows.Add(6, "Hari", "Male", "Namakkal");
return dt;
}

Using Json.net Newtonsoft DLL its very easy to get JSON data. Below written a small piece of code will convert the dataTable to JSON.

 public string ConvertDataTableToJson(DataTable table)
 {
 string jsonString = string.Empty;
 jsonString = JsonConvert.SerializeObject(table);
 return jsonString;
 }

Once we converted our DataTable to JSON, then using jQuery we can append JSON data anywhere on the Webpage.

Output

On clicking the “Convert” button the json code will be displayed as shown below.

Output fo converting datatable to json

Demo Code

Download Demo