In a project, if Ajax is used, it is often used to convert data from the background, such as a DataTable, into a JSON string. Here to share with you a DataTable to JSON method;
1 Public Static stringDttoson (DataTable DT)2 {3StringBuilder Jsonbuilder =NewStringBuilder ();4Jsonbuilder.append ("[");5 for(inti =0; i < dt. Rows.Count; i++)6 {7Jsonbuilder.append ("{");8 for(intj =0; J < dt. Columns.count; J + +)9 {TenJsonbuilder.append ("\""); One jsonbuilder.append (dt. COLUMNS[J]. ColumnName); AJsonbuilder.append ("\":\""); - jsonbuilder.append (dt. ROWS[I][J]. ToString ()); -Jsonbuilder.append ("\","); the } -Jsonbuilder.remove (Jsonbuilder.length-1,1); -Jsonbuilder.append ("},"); - } +Jsonbuilder.remove (Jsonbuilder.length-1,1); -Jsonbuilder.append ("]"); + returnjsonbuilder.tostring (); A}View Code
If it is to be list<model. Users> into JSON, you can directly use the system's
JavaScriptSerializer JSS = new JavaScriptSerializer ();
String Strjson = JSS. Serialize (list);
JavaScriptSerializer reference from using System.Web.Script.Serialization.
DataTable converted to JSON array