How to generate json a specific way from datatable

  • Thread starter Thread starter Sudip_inn
  • Start date Start date
S

Sudip_inn

Guest
i have a .net data table which is populated with sample data but when generating json from datatable then getting json this way

[{"ID":1,"Name":"Ajay"},{"ID":2,"Name":"Sanu"}]

my C# code as following

DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(Int32));
dt.Columns.Add("Name", typeof(string));

DataRow dr = dt.NewRow();
dr[0] = 1;
dr[1] = "Ajay";
dt.Rows.Add(dr);

dr = dt.NewRow();
dr[0] = 2;
dr[1] = "Sanu";
dt.Rows.Add(dr);

var lst = dt.AsEnumerable()
.Select(r => r.Table.Columns.Cast<DataColumn>()
.Select(c => new KeyValuePair<string, object>(c.ColumnName, r[c.Ordinal])
).ToDictionary(z => z.Key, z => z.Value)
).ToList();
//now serialize it
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var m= serializer.Serialize(lst);

i need to generate json below way from my datatable

[{
"columns": [{
"title": "col1_name",
"data": "col1_name"
}, {
"title": "col2_name",
"data": "col2_name"
}],
"data": [{
"col1_name": "col1 data",
"col2_name": "col2 data"
}, {
"col1_name": "col1 data",
"col2_name": "col2 data"
}]
}]

so please tell me what to change in my code for c# data table and json generation as a result i can generate my json just like above example. please help me with rectified code. thanks

Continue reading...
 
Back
Top