Hi Friends,
Thanks for visiting my blog .
In this blog , We will see how we can convert a Data Table to JSON array.
Please find the Below method
Note : Before writing the Method we need to import System.web.Extensions dll from Assemblies.
public string GetJson(DataTable dt)
{
System.Web.Script.Serialization.JavaScriptSerializer JSSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> DtRows = new List<Dictionary<string, object>>();
Dictionary<string, object> newrow = null;
//Code to loop each row in the datatable and add it to the dictionary object
foreach (DataRow drow in dt.Rows)
{
newrow = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
newrow.Add(col.ColumnName.Trim(), drow[col]);
}
DtRows.Add(newrow);
}
return JSSerializer.Serialize(DtRows);
}