c# - How convert some value to json by Newtonsoft? -
i have code homecoming "datatable ","datatable" content idstudent , avg , firstname ,namecourse , date, "datatable" content more row .
datatable row = mn.selectprogram("programstudent", attributes); jsontrans responce = new jsontrans(); responce.convert(row); //if (row.rows.count != 0) //{ // foreach (datarow result in row.rows) // { // string idstudent = result["id"].tostring(); // string avgstudent = result["avg"].tostring(); // string firstname = result["fname"].tostring(); // string date = result["date"].tostring(); // string namecourse = result["name"].tostring(); // } //}
i seek :
public string convert(datatable row) { stringbuilder sb = new stringbuilder(); stringwriter sw = new stringwriter(sb); jsonwriter jsonwriter = new jsontextwriter(sw); jsonwriter.formatting = formatting.indented; jsonwriter.writestartarray(); if (row.rows.count != 0) { foreach (datarow result in row.rows) { jsonwriter.writestartobject(); string idstudent = result["id"].tostring(); jsonwriter.writepropertyname("id"); jsonwriter.writevalue(idstudent); jsonwriter.writeendobject(); } } jsonwriter.writeendarray(); jsonwriter.close(); sw.close();
how can convert row json :
[ {idstudent:"value" ,avg :"value" , avg : "value",firstname :"value"} {idstudent:"value" ,avg :"value" , avg : "value",firstname :"value"} {idstudent:"value" ,avg :"value" , avg : "value",firstname :"value"} ]
it looks code close you're trying accomplish. if want every column nowadays in datarows, foreach loop should iterate through of table's columns. (note have changed datatable name here table clarity, , datarow name row.)
foreach (datarow row in table.rows) { jsonwriter.writestartobject(); foreach (datacolumn col in table.columns) { jsonwriter.writepropertyname(col.columnname); jsonwriter.writevalue((row[col.columnname] == null) ? string.empty : row[col.columnname].tostring()); } jsonwriter.writeendobject(); }
note illustration write out empty strings source info null. if want leave null values out entirely, perform check (row[col.columnname] == null) prior writing property name , value.
c# json
No comments:
Post a Comment