Implementation code for datasets, strings, DataTable, and objects in C # converted to JSON

Source: Internet
Author: User
Tags string methods tojson
C # objects, strings, dataTable, DataReader, datasets, object collections are converted to JSON string methods.

public class Convertjson {#region Private method///<summary>//filter special characters///</summary>//<param name= "s" ; string </param>//<returns>json string </returns> private static string String2json (string s) {Stringbui   Lder 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 (); }///<summary>//format character, date, Boolean///</summary>//<param name= "str" ></param>//<para M name= "type" ></param>///<returns></returns> PrivAte static string StringFormat (String 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; } #endregion #region List to JSON//<summary>//List to JSON///</summary>//<typeparam name= "T "></typeparam>//<param name=" list "></param>//<returns></returns> public static   String listtojson<t> (ilist<t> list) {Object obj = list[0]; return listtojson<t> (list, obj. GetType ().  Name); }//<summary>//list converted to JSON///</summary>//<typeparam name= "T1" ></typeparam>///< param name= "list" ></param>//<param name= "P" ></param>//<returns></returns> private static string listtojson<t> (ilist<t> list, string jsonname) {StringBuilder   Json = new StringBuilder (); if (string. IsNullOrEmpty (jsonname)) Jsonname = List[0]. GetType ().   Name;   Json.append ("{\" "+ Jsonname +" \ ": ["); if (list. Count > 0) {for (int i = 0; i < list. Count;     i++) {T obj = activator.createinstance<t> (); propertyinfo[] pi = obj. GetType ().     GetProperties ();     Json.append ("{"); for (int j = 0; J < Pi. Length; J + +) {Type type = Pi[j]. GetValue (List[i], null).      GetType (); Json.append ("\" "+ pi[j"). Name.tostring () + "\": "+ StringFormat (Pi[j]. GetValue (List[i], null).      ToString (), type)); if (J < Pi.      Length-1) {json.append (",");     }} json.append ("}"); if (I < list.     Count-1) {json.append (",");   }}} json.append ("]}");  return json.tostring (); Convert #endregion #region object to JSON///<summary>//object to JSON///&LT;/SUmmary>//<param name= "Jsonobject" >json objects </param>///<returns>json strings </returns> Public   static string ToJson (object jsonobject) {string jsonstring = "{"; propertyinfo[] PropertyInfo = Jsonobject.gettype ().   GetProperties (); for (int i = 0; i < propertyinfo.length; i++) {Object objectValue = Propertyinfo[i]. Getgetmethod ().    Invoke (jsonobject, NULL); String value = String.    Empty; if (ObjectValue is DateTime | | ObjectValue are GUID | | ObjectValue is TimeSpan) {value = "'" + objectvalue.tostring    () + "'";    } else if (ObjectValue is string) {value = "'" + ToJson (objectvalue.tostring ()) + "'";    } else if (ObjectValue is IEnumerable) {value = ToJson ((IEnumerable) objectValue);    } else {value = ToJson (objectvalue.tostring ()); } jsonstring + = "\" + ToJson (propertyinfo[i).   Name) + "\": "+ Value +", ";   } jsonstring.remove (Jsonstring.length-1, jsonstring.length);  return jsonstring + "}";  }Convert #endregion #region Object collection to JSON///<summary>///object collection to JSON///</summary>//<param name= "Array" &G T; object collection </param>///<returns>json string </returns> public static string ToJson (IEnumerable array) {Stri   Ng jsonstring = "{";   foreach (object item in array) {jsonstring + = ToJson (item) + ",";   } jsonstring.remove (Jsonstring.length-1, jsonstring.length);  return jsonstring + "]"; } #endregion #region Normal collection conversion JSON///<summary>//General collection conversion JSON///</summary>//<param name= "Arra Y "> Collection Object </param>//<returns>json string </returns> public static string toarraystring (IEnumerable ar   Ray) {String jsonstring = "["; foreach (object item in array) {jsonstring = ToJson (item.   ToString ()) + ",";   } jsonstring.remove (Jsonstring.length-1, jsonstring.length);  return jsonstring + "]"; } #endregion #region DataSet to JSON///<summary>//DataSet to JSON///</summary>// <param name= "DataSet" >dataset object </param>///<returns>json string </returns> public static string T   Ojson (DataSet DataSet) {string jsonstring = "{"; foreach (DataTable table in dataset.tables) {jsonstring + = "\" + table.   TableName + "\": "+ ToJson (table) +", ";   } jsonstring = Jsonstring.trimend (', ');  return jsonstring + "}"; } #endregion convert #region DataTable to JSON///<summary>//DataTable to JSON///</summary>//&LT;PA Ram Name= "table" >datatable objects </param>///<returns>json strings </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>//DataTable converted to JSON///</summary> public static string ToJson (DataTable dt, String J   Sonname) {StringBuilder Json = new StringBuilder (); if (string. IsNullOrEmpty (jsonname)) jsonname = dt.   TableName;   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 + +) {Type type = dt. ROWS[I][J].      GetType (); Json.append ("\" "+ dt. COLUMNS[J]. Columnname.tostring () + "\": "+ StringFormat (dt. ROWS[I][J].      ToString (), type)); if (J < dt.columns.count-1) {json.append (",");     }} json.append ("}"); if (i < dt.     rows.count-1) {json.append (",");   }}} json.append ("]}");  return json.tostring (); } #endregion convert #region DataReader to JSON//<summary>//DataReader to JSON///</summary>//&lt ;p Aram Name= "DataReader" >datareader objects </param>///<returns>json strings </returns> public static Stri   Ng ToJson (DbDataReader dataReader) {StringBuilder jsonstring = new StringBuilder ();   Jsonstring.append ("[");    while (Datareader.read ()) {Jsonstring.append ("{");     for (int i = 0; i < Datareader.fieldcount; i++) {Type type = Datareader.getfieldtype (i);     String strkey = Datareader.getname (i); String strvalue = Datareader[i].     ToString ();     Jsonstring.append ("\" "+ strkey +" \ ":");     strvalue = StringFormat (strvalue, type); if (I < datareader.fieldcount-1) {jsonstring.append (strvalue + ",");    } else {jsonstring.append (strvalue);   }} jsonstring.append ("},");   } datareader.close ();   Jsonstring.remove (jsonstring.length-1, 1);   Jsonstring.append ("]");  return jsonstring.tostring (); } #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.