Table of Contents
Convert DataTable to JSON in C#
We have already explained Convert DataTable to List C#, Is Application running already in WPF, Extension Method in C#, Reflection Introduction c#, Insert data into Database table using SQLBulkCopy class in C#, as keyword C#, Import/Upload Excel file in asp.net with C#, The Microsoft Jet database engine cannot open the file. It is already opened exclusively by another user, Call method after specific time interval C#, Alert from code behind asp.net,required field validator in asp.net,Difference between RegisterClientScriptBlock and RegisterStartupScript asp.net, Difference between ref and out parameters.
Today we will look “How to convert DataTable to JSON in C#!!!”
There are 3 different ways to convert DataTable to JSON in C#:
- Using StringBuilder
- Using JavaScriptSerializer
- Using Newtonsoft.
Lets say we have below DataTable available with us
public static DataTable getDataTable() { DataTable dt = new DataTable(); dt.Columns.Add("EmployeeID", typeof(Int32)); dt.Columns.Add("EmployeeName", typeof(string)); dt.Rows.Add(1, "Pole"); dt.Rows.Add(2, "Bhavin"); dt.Rows.Add(3, "Sohil"); dt.Rows.Add(4, "Arvind"); dt.Rows.Add(5, "Aditya"); return dt; }
Sample JSON string would be as below:
1. Using StringBuilder
Let try to build JSON string from DataTable using StringBuilder. Refer below code snippet:
public string DataTableToJSONUsingStringBuilder(DataTable table) { var JSONString = new StringBuilder(); if (table.Rows.Count > 0) { JSONString.Append("["); foreach (DataRow dr in table.Rows) { JSONString.Append("{\"EmployeeID\":\"" + dr["EmployeeID"] + "\",\"EmployeeName\":\"" + dr["EmployeeName"] + "\"},"); } JSONString.Remove(JSONString.Length - 1, 1).Append("]"); } return JSONString.ToString(); }
2. Using JavaScriptSerializer
Add using System.Web.Script.Serialization; namespace.
public string DataTableToJSONWithJavaScriptSerializer(DataTable table) { JavaScriptSerializer jsSerializer = new JavaScriptSerializer(); List<Dictionary<string, object>> parentRow = new List<Dictionary<string, object>>(); Dictionary<string, object> childRow; foreach (DataRow row in table.Rows) { childRow = new Dictionary<string, object>(); foreach (DataColumn col in table.Columns) childRow.Add(col.ColumnName, row[col]); parentRow.Add(childRow); } return jsSerializer.Serialize(parentRow); }
3. Newtonsoft
Download Newtonsoft dll from Newtonsoft Download Link.
public string DataTableToJSONWithJSONNet(DataTable table) { string JSONString = string.Empty; JSONString = JsonConvert.SerializeObject(table); return JSONString; }
You can also download Convert DataTable To JSON
Thanks folks for reading my post and kindly leave your feedback.