//////////////////// Convert datatable to json
////// Using Namespace
////// Using Namespace
using System.Web.Script.Serialization;
Steps: Application Root >> Right click >> Add >> Reference
>> Framework >> System.web.Extensions
public static string DataTable_JSON(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);
}
///////////////// Dataset to Json
public static string DataSet_JSON(DataSet ds)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
///////// If
add json without root name of the json
// System.Collections.ArrayList root = new
System.Collections.ArrayList();
Dictionary<string, object> _clientDictionary = new Dictionary<string, object>();
List<Dictionary<string, object>> table;
Dictionary<string, object> data;
foreach (DataTable dt in ds.Tables)
{
table = new List<Dictionary<string, object>>();
foreach (DataRow dr in dt.Rows)
{
data = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
data.Add(col.ColumnName, dr[col]);
}
table.Add(data);
}
_clientDictionary.Add(dt.TableName, table);
/////////
If add json without root name of the json
//root.Add(table);
}
return serializer.Serialize(_clientDictionary);
}
No comments:
Post a Comment