Convert datatable to JSON in C# -
- i want records database
datatable
. - then convert
datatable
json object. - return json object javascript function.
i use this code calling:
string result = jsonconvert.serializeobject(datatabletodictionary(queryresult, "title"), newtonsoft.json.formatting.indented);
to convert datatable json, works correctly , return following:
{ "1": { "viewcount": 703, "clickcount": 98 }, "2": { "viewcount": 509, "clickcount": 85 }, "3": { "viewcount": 578, "clickcount": 86 }, "4": { "viewcount": 737, "clickcount": 108 }, "5": { "viewcount": 769, "clickcount": 130 } }
but return following:
{"records":[ { "title": 1, "viewcount": 703, "clickcount": 98 }, { "title": 2, "viewcount": 509, "clickcount": 85 }, { "title": 3, "viewcount": 578, "clickcount": 86 }, { "title": 4, "viewcount": 737, "clickcount": 108 }, { "title": 5, "viewcount": 769, "clickcount": 130 } ]}
how can this?
this code snippet convert datatable json string in c#, vb.net might you. uses system.web.script.serialization.javascriptserializer serialize contents json format:
public string convertdatatabletostring() { datatable dt = new datatable(); using (sqlconnection con = new sqlconnection("data source=sureshdasari;initial catalog=master;integrated security=true")) { using (sqlcommand cmd = new sqlcommand("select title=city,lat=latitude,lng=longitude,description locationdetails", con)) { con.open(); sqldataadapter da = new sqldataadapter(cmd); da.fill(dt); system.web.script.serialization.javascriptserializer serializer = new system.web.script.serialization.javascriptserializer(); list<dictionary<string, object>> rows = new list<dictionary<string, object>>(); dictionary<string, object> row; foreach (datarow dr in dt.rows) { row = new dictionary<string, object>(); foreach (datacolumn col in dt.columns) { row.add(col.columnname, dr[col]); } rows.add(row); } return serializer.serialize(rows); } } }
Comments
Post a Comment