Convert DataTable into Json C#

Convert DataTable into Json C#

DataTable to Json:

Sometimes developer may in need of Converting DataTable into Json format. There are many ways to convert DataTable into JSON format. The most common way is looping using StringBuilder but for bulk iteration this method is not recommended, still developer needs to iterate over limited data they can try below code:

StringBuilder:

using System.Text;
public string ConvertDatamyDataTableToJson(DatamyDataTable myDataTable)   
{  
    var JsonStringBuilder = new StringBuilder();  
    if (myDataTable.Rows.Count > 0)   
    {  
        JsonStringBuilder.Append("[");  
        for (int i = 0; i < myDataTable.Rows.Count; i++)   
        {  
            JsonStringBuilder.Append("{");  
            for (int j = 0; j < myDataTable.Columns.Count; j++)   
            {  
                if (j < myDataTable.Columns.Count - 1)   
                {  
                    JsonStringBuilder.Append("\"" + myDataTable.Columns[j].ColumnName.ToString() + "\":" + "\"" + myDataTable.Rows[i][j].ToString() + "\",");  
                }   
                else if (j == myDataTable.Columns.Count - 1)   
                {  
                    JsonStringBuilder.Append("\"" + myDataTable.Columns[j].ColumnName.ToString() + "\":" + "\"" + myDataTable.Rows[i][j].ToString() + "\"");  
                }  
            }  
            if (i == myDataTable.Rows.Count - 1)   
            {  
                JsonStringBuilder.Append("}");  
            }   
            else   
            {  
                JsonStringBuilder.Append("},");  
            }  
        }  
        JsonStringBuilder.Append("]");  
    }  
    return JsonStringBuilder.ToString();  
}

Note: We are using StringBuilder class hence, developer must include System.Text library as using.

This is straight forward looping which takes DataTable as input parameter and iterate over each row/column to build JSON format.

JavaScript Serializer:

Another method is using JavaScriptSerializer class which offers rich properties and methods to establish a asynchronous internal communication layer to serialize or deserialize data.

This library is a part of System.Web.Script.Serialization object model. which must be reference in your code as below:

using System.Web.Script.Serialization;
public string DatamyDataTableToJsonUsingJavaScriptSerializer(DatamyDataTable myDataTable) 
{  
    JavaScriptSerializer jsSerializer = new JavaScriptSerializer();  
    List > parentRow = new List <Dictionary<string,object>>();  
    Dictionary <string,object> childRow;  
    foreach(DataRow row in myDataTable.Rows) 
    {  
        childRow = new Dictionary <string,object>();  
        foreach(DataColumn col in myDataTable.Columns) 
        {  
            childRow.Add(col.ColumnName, row[col]);  
        }  
        parentRow.Add(childRow);  
    }  
    return jsSerializer.Serialize(parentRow);  
}

Newtonsoft JSON.Net:

Json.Net (Newtonsoft) also offers a method to Serialize object into Json. Lets have a look at below code using Newtonsoft.Json library which offers JSONConvert.SerializeObject method:

using Newtonsoft.JSON;  
public string DataTableToJSONWithJSONNet(DataTable myDataTable) {  
   string JsonString=string.Empty;  
   JsonString = JSONConvert.SerializeObject(myDataTable);  
   return JsonString;
}

Next>>Populating DataTable with DataSet SQL Server C#

Leave a Reply

Your email address will not be published.