Json is (Javascript object notation) it key/value pairs. its easy to read , write and human editable format. its light wight and the most widely used format for interchanging data on the Website.
We can convert Datatable or Dataset to JSON string in many ways, the below example is the one of the best function to convert datatable to json string. Just pass your datatable to GetDataTableToJson(Datatable) function, this function will return Json string as a return type.
Code:
//Convert DataTable to JSON String
public string
GetDataTableToJson(DataTable dt)
{
System.Web.Script.Serialization.JavaScriptSerializer
jserializer = new
System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>>
lstrows = new List<Dictionary<string,
object>>();
Dictionary<string,
object> rowvalue;
foreach (DataRow
dr in dt.Rows)
{
rowvalue = new Dictionary<string, object>();
foreach (DataColumn col in
dt.Columns)
{
rowvalue.Add(col.ColumnName, dr[col]);
}
lstrows.Add(rowvalue);
}
return jserializer.Serialize(lstrows);
} The above method will give you the JONS formatted string as a output. Hope this will help you to use in your project.
No comments:
Post a Comment