3 Ways to Convert DataTable to JSON String in ASP.NET C#

This article explains how to convert a DataTable to JSON in ASP.NET C#. Learn how to serialize a DataTable to a JSON array in C# OR how to return a JSON String from a DataTable in ASP.NET C#.

This article explains how to convert a DataTable to JSON in ASP.NET C#. In other words, how to serialize a DataTable to a JSON array in C#. In other words how to return a JSON String from a DataTable in ASP.NET C#. There are 3 ways to do this and they are using StringBuilder, JavaScriptSerializer or using JSON.Net DLL (from Newtonsoft).

JSON

JavaScript Object Notation (JSON) is a lightweight data-interchange format. It is easy for humans to read and write and 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 and so on.

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.

The following is the procedure for converting a DataTable to a JSON object in C#:
  1. Convert DataTable to JSON using StringBuilder.
  2. Convert DataTable to JSON using JavaScriptSerializer.
  3. Convert DataTable to JSON using JSON.Net DLL.

Using any one of the preceding methods will serialize a .NET DataTable to a JSON String in C#.

First we will get records from the database (Microsoft SQL Server) into a DataTable or we can also add dynamic rows to our DataTable. So our code looks as in the following:

  1. public DataTable getData()   
  2. {  
  3.     DataTable dt = new DataTable();  
  4.     dt.Columns.Add("UserId"typeof(Int32));  
  5.     dt.Columns.Add("UserName"typeof(string));  
  6.     dt.Columns.Add("Education"typeof(string));  
  7.     dt.Columns.Add("Location"typeof(string));  
  8.     dt.Rows.Add(1, "Satinder Singh""Bsc Com Sci""Mumbai");  
  9.     dt.Rows.Add(2, "Amit Sarna""Mstr Com Sci""Mumbai");  
  10.     dt.Rows.Add(3, "Andrea Ely""Bsc Bio-Chemistry""Queensland");  
  11.     dt.Rows.Add(4, "Leslie Mac""MSC""Town-ville");  
  12.     dt.Rows.Add(5, "Vaibhav Adhyapak""MBA""New Delhi");  
  13.     return dt;  
  14. }  
Then convert the DataTable into a JSON object using any of the previous methods that return the JSON object. Let’s go through each method step-by-step.

Method 1

Convert DataTable to JSON using StringBuilder.

This is how the JSON sample data looks: {"firstName":"Satinder", "lastName":"Singh"}.

JSON objects are written inside curly braces and can contain multiple name/values pairs.

So using StringBuilder we can create a similar JSON Structured String.

Since we are using StringBuilder we need to import the System.Text namespace in our page as in the following:
  1. Using System.Text;  
The following code will generate a JSON string. Here we are making a for loop over our DataTable rows and columns. Fetch the data (values) and append it to our JSONString StringBuilder. This is how our code looks:
  1. public string DataTableToJSONWithStringBuilder(DataTable table)   
  2. {  
  3.     var JSONString = new StringBuilder();  
  4.     if (table.Rows.Count > 0)   
  5.     {  
  6.         JSONString.Append("[");  
  7.         for (int i = 0; i < table.Rows.Count; i++)   
  8.         {  
  9.             JSONString.Append("{");  
  10.             for (int j = 0; j < table.Columns.Count; j++)   
  11.             {  
  12.                 if (j < table.Columns.Count - 1)   
  13.                 {  
  14.                     JSONString.Append("\"" + table.Columns[j].ColumnName.ToString() + "\":" + "\"" + table.Rows[i][j].ToString() + "\",");  
  15.                 }   
  16.                 else if (j == table.Columns.Count - 1)   
  17.                 {  
  18.                     JSONString.Append("\"" + table.Columns[j].ColumnName.ToString() + "\":" + "\"" + table.Rows[i][j].ToString() + "\"");  
  19.                 }  
  20.             }  
  21.             if (i == table.Rows.Count - 1)   
  22.             {  
  23.                 JSONString.Append("}");  
  24.             }   
  25.             else   
  26.             {  
  27.                 JSONString.Append("},");  
  28.             }  
  29.         }  
  30.         JSONString.Append("]");  
  31.     }  
  32.     return JSONString.ToString();  
  33. }  
Method 2

Convert the DataTable to JSON using JavaScriptSerializer.

Since we are using JavaScriptSerializer we first need to import the System.Web.Script.Serialization namespace into our page as in the following code:
  1. using System.Web.Script.Serialization;  
The JavaScriptSerializer class is used internally by the asynchronous communication layer to serialize and deserialize the data.

To serialize an object, use the Serialize method. To deserialize a JSON string, use the Deserialize or DeserializeObject methods.

Here we use the serialize method to get the JSON format data. So our code looks as in the following:
  1. public string DataTableToJSONWithJavaScriptSerializer(DataTable table) 
  2. {  
  3.     JavaScriptSerializer jsSerializer = new JavaScriptSerializer();  
  4.     List < Dictionary < stringobject >> parentRow = new List < Dictionary < stringobject >> ();  
  5.     Dictionary < stringobject > childRow;  
  6.     foreach(DataRow row in table.Rows) 
  7.     {  
  8.         childRow = new Dictionary < stringobject > ();  
  9.         foreach(DataColumn col in table.Columns) 
  10.         {  
  11.             childRow.Add(col.ColumnName, row[col]);  
  12.         }  
  13.         parentRow.Add(childRow);  
  14.     }  
  15.     return jsSerializer.Serialize(parentRow);  
  16. }  
Method 3

Convert DataTable to JSON using JSON.Net DLL (Newtonsoft).

Now in this method we will convert our C# Datatable to JSON using the Newtonsoft DLL.

For this first we need to download JSON.Net DLL. We can download it from Nuget.org and then import the Newtonsoft.JSON namespace into our page as in the following code. JSON.NET is a popular high-performance JSON framework for .NET.
  1. using Newtonsoft.JSON;  
  2.   
  3. public string DataTableToJSONWithJSONNet(DataTable table) {  
  4.    string JSONString=string.Empty;  
  5.    JSONString = JSONConvert.SerializeObject(table);  
  6.    return JSONString;  
  7. }  
Yes we are done with JSON, here's the output:

datatable to JSON