Using System; Using System.Collections.Generic; Using System.Data; Using System.Linq; Using System.Text; Using System.Web; ////// Datatableconvertjson Summary Description ///public class Datatableconvertjson {public Datatableconvertjson () {/////TODO: Add constructor logic here } #region DataTable into JSON format//// DataTable converted to JSON format ////////
public static string Datatable2json (DataTable dt) {StringBuilder Jsonbuilder = new StringBuilder (); Jsonbuilder.append ("{\" "); Jsonbuilder.append (dt. TableName); Jsonbuilder.append ("["); Jsonbuilder.append ("["); for (int i = 0; i < dt. Rows.Count; i++) {jsonbuilder.append ("{"); for (int j = 0; j < dt. Columns.count; J + +) {jsonbuilder.append ("\" "); Jsonbuilder.append (dt. COLUMNS[J]. ColumnName); Jsonbuilder.append ("\": \ ""); Jsonbuilder.append (dt. ROWS[I][J]. ToString ()); Jsonbuilder.append ("\", "); } jsonbuilder.remove (jsonbuilder.length-1, 1); Jsonbuilder.append ("},"); } jsonbuilder.remove (jsonbuilder.length-1, 1); Jsonbuilder.append ("]"); Jsonbuilder.append ("}"); return jsonbuilder.tostring (); } #endregion DataTable into JSON format #region DataSet into JSON format// /// DataSet converted to JSON format /////DataSet///
public static string Dataset2json (DataSet ds) {StringBuilder json = new StringBuilder (); foreach (DataTable dt in DS. Tables) {json. Append ("{\" "); Json. Append (dt. TableName); Json. Append ("\": "); Json. Append (Datatable2json (DT)); Json. Append ("}"); } return JSON. ToString (); } #endregion///// MSDN ///////////
public static string Datatabletojson (String jsonname, DataTable dt) {StringBuilder Json = new STRINGB Uilder (); Json.append ("{\" "+ Jsonname +" \ ": ["); if (dt. Rows.Count > 0) {for (int i = 0; i < dt. Rows.Count; i++) {json.append ("{"); for (int j = 0; j < dt. Columns.count; J + +) {json.append ("\" + dt. COLUMNS[J]. Columnname.tostring () + "\": \ "" + dt. ROWS[I][J]. ToString () + "\" "); if (J < dt. columns.count-1) {json.append (","); }} json.append ("}"); if (i < dt. rows.count-1) {json.append (","); }}} json.append ("]}"); return json.tostring (); } }