5 code instances of converting a DataTable to JSON in C #

Source: Internet
Author: User
Tags tojson
Example one:

<summary>//DataTable converted to JSON///</summary>/<param name= "table" >datatab    Le object </param>///<returns>json string </returns> public static string ToJson (DataTable dt)        {StringBuilder jsonstring = new StringBuilder ();        Jsonstring.append ("["); DataRowCollection DRC = dt.        Rows; for (int i = 0; i < DRC. Count;            i++) {jsonstring.append ("{"); for (int j = 0; j < dt. Columns.count; J + +) {string strkey = dt. COLUMNS[J].                ColumnName; String strvalue = Drc[i][j].                ToString (); Type type = dt. COLUMNS[J].                DataType;                Jsonstring.append ("\" "+ strkey +" \ ":");                strvalue = StringFormat (strvalue, type); if (J < dt.                columns.count-1) {jsonstring.append (strvalue + ",");                   } else { Jsonstring.append (strvalue);        }} jsonstring.append ("},");        } jsonstring.remove (jsonstring.length-1, 1);        Jsonstring.append ("]");    return jsonstring.tostring (); }///<summary>//format character, date, Boolean///</summary>//<param name= "str" ></param>// /<param name= "type" ></param>///<returns></returns> private static string StringFormat (str            ing str, type type) {if (type = = typeof (String)) {str = String2json (str);        str = "\" "+ str +" \ ";        } else if (type = = typeof (DateTime)) {str = "\" "+ str +" \ ""; } else if (type = = typeof (bool)) {str = str.        ToLower (); } else if (type! = typeof (String) && string.        IsNullOrEmpty (str)) {str = "\" "+ str +" \ ";    } return str;    }//<summary>///filter special characters</summary>//<param name= "S" > String </param>//<returns>json string </returns> Priva        Te static string String2json (string s) {StringBuilder sb = new StringBuilder ();            for (int i = 0; i < s.length; i++) {char c = s.tochararray () [i]; Switch (c) {case ' \ ': SB. Append ("\\\");                Break Case ' \ \ ': SB. Append ("\\\\");                Break Case '/': SB. Append ("\\/");                Break Case ' \b ': sb. Append ("\\b");                Break Case ' \f ': sb. Append ("\\f");                Break Case ' \ n ': sb. Append ("\\n");                Break Case ' \ R ': SB. Append ("\\r");                Break Case ' \ t ': sb. Append ("\\t");                Break DEFAULT:SB. Append (c);            Break }} RetuRN sb.    ToString (); }

Instance two:

 public static string Createjsonparameters (DataTable dt) {/**//**//**//*/***************** * Without goingin to the depth of the functioning of This method, I'll try to give an overview * as soon as the This method gets a DataTable it starts to convert it int          o JSON String, * It takes each row and with each row it grabs the cell name and its data.          * This kind of JSON was very usefull when developer has to have the Column name of the. * Values Can is Access on the clien in the this. Obj. head[0].<columnname> * Note:one negative point.         By this method, user'll is not being able to call any cell by its index. * *************************************************************************/StringBuilder jsonstring = new STR            Ingbuilder (); Exception handling if (dt! = null && dt.           Rows.Count > 0) {Jsonstring.append ("{");                Jsonstring.append ("\" t_blog\ ": ["); for (int i = 0; i < dt. Rows.Count;                    i++) {jsonstring.append ("{"); for (int j = 0; j < dt. Columns.count; J + +) {if (J < dt. columns.count-1) {jsonstring.append ("\" "+ dt.) COLUMNS[J]. Columnname.tostring () + "\": "+" \ "" + dt. ROWS[I][J].                        ToString () + "\", "); } else if (j = = dt. columns.count-1) {jsonstring.append ("\" "+ dt.) COLUMNS[J]. Columnname.tostring () + "\": "+" \ "" + dt. ROWS[I][J].                        ToString () + "\" "); }}/**//**//**//*end of string*/if (i = = DT .  rows.count-1) {jsonstring.append ("}");                  } else {jsonstring.append ("},");                }} jsonstring.append ("]}");            return jsonstring.tostring ();            } else {return null; }        }

Effect:
{"T_blog":
[
{"id": "+", "title": "Beijing Olympic Opening Ceremony", "Addtime": "2008-08-08"},
{"id": "Net", "title": "Network Culture", "Addtime": "2008-09-12"},
{"id": "+", "title": "Beijing Rains", "addtime": "2008-09-19"},
{"id": "+", "title": "Shenzhen Metro Pass", "Addtime": "2008-09-25"}
]
}

Example three:

<summary>////Convert a data table into a JSON string that can be converted directly to a two-dimensional array at the client. </summary>//<param name= "source" > the table that needs to be converted.        </param>///<returns></returns> public static string Datatabletojson (DataTable source) { if (source.        Rows.Count = = 0) return "";        StringBuilder sb = new StringBuilder ("["); foreach (DataRow row in source. Rows) {sb.            Append ("["); for (int i = 0; i < source. Columns.count; i++) {sb. Append (' "' + row[i].            ToString () + "\", "); } sb. Remove (sb.)            Length-1, 1); Sb.        Append ("],"); } sb. Remove (sb.)        Length-1, 1); Sb.        Append ("]"); Return SB.    ToString ();  }///<summary>//Reverse JSON data to reception///</summary>/<param name= "DT" > Data sheet </param>// <returns>json strings </returns> public string createjsonparameters (DataTable dt) {StringBuilder Json String = nEW StringBuilder (); Exception handling if (dt! = null && dt.            Rows.Count > 0) {jsonstring.append ("{");            Jsonstring.append ("\" tableinfo\ ": ["); for (int i = 0; i < dt. Rows.Count;                i++) {jsonstring.append ("{"); for (int j = 0; j < dt. Columns.count; J + +) {if (J < dt. columns.count-1) {jsonstring.append ("\" "+ dt.) COLUMNS[J]. Columnname.tostring () + "\": "+" \ "" + dt. ROWS[I][J].                    ToString () + "\", "); } else if (j = = dt. columns.count-1) {jsonstring.append ("\" "+ dt.) COLUMNS[J]. Columnname.tostring () + "\": "+" \ "" + dt. ROWS[I][J].                    ToString () + "\" "); }}/**//*end of string*/if (i = = dt.                  ROWS.COUNT-1) {  Jsonstring.append ("}");                } else {jsonstring.append ("},");            }} jsonstring.append ("]}");        return jsonstring.tostring ();        } else {return null; }    }

Instance four:

public class Datatableconvertjson {#region DataTable converted to JSON format//<summary>//DataTable Convert to JSON format///</summary>//<param name= "DT" ></param>//<returns>&lt ;/returns> public static string Datatable2json (DataTable dt) {StringBuilder Jsonbuilder = n            EW 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 (); } Convert #endregion DataTable to JSON format #region DataSet to JSON format///<summary>///DataSet to J Son format///</summary>//<param name= "DS" >DataSet</param>//<returns>& lt;/returns> public static string Dataset2json (DataSet ds) {StringBuilder json = new string            Builder (); foreach (DataTable dt in DS. Tables) {json.                Append ("{\" "); Json. Append (dt.                TableName); Json.                Append ("\": "); Json.                Append (Datatable2json (DT)); Json.            Append ("}"); } return JSON.        ToString (); } #endregIon//<summary>//MSDN//</summary>//<param name= "Jsonname" ></pa ram>//<param name= "DT" ></param>///<returns></returns> public static S            Tring Datatabletojson (String jsonname, DataTable dt) {StringBuilder Json = new StringBuilder ();            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 (); }    }

Instance five:

Convert #region DataTable to JSON string instance method//<summary>///GETCLASSTYPEJOSN Summary description///</summary>public class getclasstypejosn:ihttphandler{///<summary>///File name: DataTable and JSON string mutual transfer//Copyright: Copyrights (C) Create Family Wealth LIANGJW///Create Logo: 2013-08-03//</summary>//Usage Description Instance public void ProcessRequest (Httpconte XT context) {context.        Response.ContentType = "Application/json"; Context.        Response.Charset = "Utf-8"; HttpRequest req = context.        Request; String method = Req["Method"]. Tostr ().       ToLower ();            Get Contract Details List DataTable converted to JSON string if (method = = "Txtdate") {string json = ""; BO.            MAKECONTRACTMX BLL = new MAKECONTRACTMX (); DataSet ds = BLL.            Getdatatable (); if (ds. Tables.count > 0) {JSON =tojson (ds.            Tables[0]); } context.            Response.Write (JSON);        Return        }} public bool IsReusable {get {return false; }}} #endregion #region json string into a DataTable instance method public DataTable jsontodatatable (JSON) {DataTable D         t= todatatable (JSON);    return DT; } #endregion convert #region DataTable to JSON string///<summary>//DataTable object to JSON string///</sum mary>//<param name= "DT" ></param>///<returns></returns> public static string Tojso        N (this DataTable dt) {JavaScriptSerializer JavaScriptSerializer = new JavaScriptSerializer (); Javascriptserializer.maxjsonlength = Int32.MaxValue;        Obtain the maximum value ArrayList ArrayList = new ArrayList (); foreach (DataRow datarow in dt.  Rows) {dictionary<string, object> Dictionary = new dictionary<string, object> (); Instantiate a parameter set of foreach (DataColumn DataColumn in dt. Columns) {dictionary. ADD (Datacolumn.columnname, Datarow[datacolumn.columnname]. Tostr ()); } arraylist.add (dictionary);  Add a key value to the ArrayList collection} return Javascriptserializer.serialize (arrayList); Returns a JSON string} #endregion #region JSON string converted to a DataTable data set///<summary>///JSON string converted to DATATABL e data Set//</summary>//<param name= "JSON" ></param>//<returns></returns> Pub  Lic static DataTable todatatable (This string json) {datatable datatable = new DataTable ();        Instantiate a DataTable result;            try {javascriptserializer JavaScriptSerializer = new JavaScriptSerializer (); Javascriptserializer.maxjsonlength = Int32.MaxValue;            Get the maximum value ArrayList ArrayList = javascriptserializer.deserialize<arraylist> (JSON);                 if (Arraylist.count > 0) {foreach (dictionary<string, object> Dictionary in ArrayList) {if (dictionary. keys.count<string> () = = 0)                    {result = DataTable;                    return result;  } if (DataTable.Columns.Count = = 0) {foreach (String current in dictionary. Keys) {DATATABLE.COLUMNS.ADD (current, dictionary[current].                        GetType ());                    }} DataRow DataRow = Datatable.newrow (); foreach (String current in dictionary.                    Keys) {Datarow[current] = dictionary[current]; } dataTable.Rows.Add (DataRow);        Loop add row to DataTable}}}} = {} result = DataTable;    return result; #endregion #region converted to string string type///<summary>///Convert to String String type///</summary>//&lt ;p Aram Name= "S" > get the value that needs to be converted </param&Gt <param name= "format" > number of bits required to format </param>//<returns> return a new string </returns> public static str        ing tostr (This object s, string format = "") {string result = "";            try {if (format = = "") {result = S.tostring (); } else {result = string.            Format ("{0:" + format + "}", s);    }} catch {} return result; } #endregion
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.