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]);
        return serializer.Serialize(tableRows);


Hey! I'm Anil Singh. I author this blog. I'm Active Blogger, Programmer. I love learning new technologies, programming, blogging and participating the forum discussions more...
My Blogs - and
My Books - Interview Questions and Answers Books- Get Your Book in 15+ Digital Stores Worldwide..

You Might Also Like Powered by Blogger.
ASK Questions