convert data-table to json string

How to convert DataTable to JSON string using C#.Net?

Hello everyone, I going to share the code sample for convert Data Table into JSON string using JavaScript Serializer as given below.

public class Converter
{
    /// <summary>
    /// This method is used to convert DataTable into JSON string using JavaScript Serializer.
    /// </summary>
    public String ConvertToJSONString(DataTable dataTable)
    {
        JavaScriptSerializer serializer = new JavaScriptSerializer();

        List<Dictionary<String, Object>> tableRows = new List<Dictionary<String, Object>>();

        Dictionary<String, Object> row;

        foreach (DataRow dr in dataTable.Rows)
        {
            row = new Dictionary<String, Object>();
            foreach (DataColumn col in dataTable.Columns)
            {
                row.Add(col.ColumnName, dr[col]);
            }
            tableRows.Add(row);
        }
        return serializer.Serialize(tableRows);
    }
}




ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..

My Tech Blog - https://www.code-sample.com/
My Books - Book 1 and Book 2

www.code-sample.com/. Powered by Blogger.
^