In this post, we want to discuss the efficient way to convert DataTable to JSON String using C#. Before we get started, if you want to know about exporting GridView data to Excel, please go through the following article: Export GridView to Excel with advanced features.

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.

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/value 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: 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:

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: 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:

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.

Convert DataTable to JSON String in ASP.NET C#

The article was published on October 22, 2019 @ 2:27 AM

Leave a Comment