Convert JSON format helper class

Source: Internet
Author: User

Using system;using system.collections.generic;using system.text;using system.reflection;using System.Data;using  System.collections;namespace aimscommon{//<summary>///Convert JSON Format help class///</summary> public class Jsonhelper {//<summary>///generic interface to JSON///</summary>//<typeparam name        = "T" ></typeparam>//<param name= "list" ></param>//<returns></returns> public static string ilisttojson<t> (ilist<t> list) {StringBuilder SB = new Stringbuil            Der (); Sb.            Append ("["); foreach (T-T in list) {sb.            Append (Objecttojson (t) + ","); } string _temp = sb. ToString ().            TrimEnd (', ');            _temp + = "]";        return _temp; }///<summary>///generic interface to JSON///</summary>//<typeparam name= "T" ></ty peparam>//&LT;param name= "List" ></param>//<param name= "ClassName" ></param>//<returns>{" Rows ": [{" c_id ":" 21bb6911-af52-42a4-9732-24a6e8384411 "," eav_id ":" 4a9fe8ca-112a-47c0-b074-229837cfe6e6 "," e_id ":" Cfe929e3-accd-4efb-910b-07705077b6d6 "," ea_id ":" "," Ea_name ":" 555 "," Eav_value ":" 555 "," Eav_memo ":" "," Sud ":" 0 "}]}            </returns> public static string ilisttojson<t> (ilist<t> list, string ClassName) {            StringBuilder sb = new StringBuilder (); Sb.            Append ("{\" "+ ClassName +" \ ": ["); foreach (T-T in list) {sb.            Append (Objecttojson (t) + ","); } string _temp = sb. ToString ().            TrimEnd (', ');            _temp + = "]}";        return _temp; }///<summary>//object to JSON///</summary>//<typeparam name= "T" ></type param>//<param name= "T" ></param>///<returns>{"sm_id": "+", "sm_IMG ":" Title.gif "," Sm_memo ":" Current Location: Club Services-Guest Management-guest list "}</returns> public static string objecttojson<t> (T            T) {StringBuilder SB = new StringBuilder ();            String json = ""; if (t! = null) {sb.                Append ("{"); Propertyinfo[] Properties = T.gettype ().                GetProperties (); foreach (PropertyInfo pi in properties) {sb. Append ("\" "+ pi.)                    Name.tostring () + "\" "); Sb.                    Append (":"); Sb. Append ("\" "+ pi.)                    GetValue (t, null) + "\" "); Sb.                Append (","); } JSON = sb. ToString ().                TrimEnd (', ');            JSON + = "}";        } return JSON; }///<summary>//object to JSON (reload)///</summary>//<typeparam name= "T" ></ typeparam>//<param name= "T" ></param>///<param name= "ClassName" ></param>//<returns>{"menu": [{"sm_id": "", "sm_img": "Title.gif", "Sm_memo": "Current Location: Club Service-Guest Management-guest list"}]}</re turns> public static string objecttojson<t> (T T, string ClassName) {StringBuilder SB =            New StringBuilder (); Sb.            Append ("{\" "+ ClassName +" \ ": [");            String json = ""; if (t! = null) {sb.                Append ("{"); Propertyinfo[] Properties = T.gettype ().                GetProperties (); foreach (PropertyInfo pi in properties) {sb. Append ("\" "+ pi.) Name.tostring () + "\" ");//. ToLower () sb.                    Append (":"); Sb. Append ("\" "+ pi.)                    GetValue (t, null) + "\" "); Sb.                Append (","); } JSON = sb. ToString ().                TrimEnd (', ');            JSON + = "}]}";        } return JSON; }///<summary>//List into JSON///</summary>// <typeparam name= "T" ></typeparam>//<param name= "Jsonname" ></param>//<param Name= "IL" ></param>///<returns></returns> public static string objecttojson<t> (I            List<t> IL, String jsonname) {StringBuilder Json = new StringBuilder ();            Json.append ("{\" "+ Jsonname +" \ ": ["); if (IL. Count > 0) {for (int i = 0; i < IL. Count;                    i++) {T obj = activator.createinstance<t> (); Type type = obj.                    GetType (); propertyinfo[] PiS = type.                    GetProperties ();                    Json.append ("{"); for (int j = 0; J < PiS. Length; J + +) {json.append ("\" + pis[j]. Name.tostring () + "\": \ "" + pis[j].                        GetValue (Il[i], null) + "\" "); if (J < PiS.               LENGTH-1) {             Json.append (",");                    }} json.append ("}"); if (I < IL.                    Count-1) {json.append (",");            }}} json.append ("]}");        return json.tostring (); }///<summary>///Convert an array to a JSON-formatted string///</summary>//<typeparam name= "T" > Data types, such as String,int ...</typeparam>//<param name= "list" > Generics list</param>//<param name= Class name for "PropertyName" >json </param>///<returns></returns> public static string Arraytojson            <T> (list<t> List, String propertyname) {StringBuilder sb = new StringBuilder (); if (list. Count > 0) {sb.                Append ("[{\" "); Sb.                Append (PropertyName); Sb.                Append ("\": ["); foreach (T T in list) {sb.                    Append ("\" "); Sb.                    Append (T.tostring ()); Sb.                Append ("\", "); } string _temp = sb.                ToString (); _temp = _temp.                TrimEnd (', ');                _temp + = "]}]";            return _temp;        } else return ""; }///<summary>//DataTable to JSON///</summary>//<param name= "DT" >table        Datasets </param>//<param name= "Dtname" >json name </param>//<returns></returns> public static string Datatabletojson (DataTable dt, string dtname) {StringBuilder sb = new Stringbui            Lder (); Sb.            Append ("{\" "); Sb.            Append (Dtname); Sb.            Append ("\": ["); if (datatablehelper.isexistrows (dt)) {foreach (DataRow dr in DT). Rows) {sb.     Append ("{");               foreach (DataColumn dc in Dr. Table.columns) {sb.                        Append ("\" "); Sb. Append (DC.                        ColumnName); Sb.                        Append ("\": \ ""); if (DR[DC]! = NULL && DR[DC]! = DBNull.Value && DR[DC]. ToString () = "" ") sb. Append (DR[DC]).                        Replace ("\ \", "/"); Else sb.                        Append (" "); Sb.                    Append ("\", "); } SB = sb. Remove (sb.)                    Length-1, 1); Sb.                Append ("},"); } SB = sb. Remove (sb.)            Length-1, 1); } sb.            Append ("]}"); Return Jsoncharfilter (sb.)        ToString ()); }///<summary>//Data line to JSON///</summary>//<param name= "Dr" > Data row </par am>//<returns></returns> public static string Datarowtojson (DataRow DR) {StringBuilder sb = new StringBuilder (); Sb.            Append ("{"); foreach (DataColumn dc in Dr. Table.columns) {sb.                Append ("\" "); Sb. Append (DC.                ColumnName); Sb.                Append ("\": \ ""); if (DR[DC]! = NULL && DR[DC]! = DBNull.Value && DR[DC]. ToString () = "" ") sb.                Append (DR[DC]); Else sb.                Append (" "); Sb.            Append ("\", "); } SB = sb. Remove (0, sb.)            LENGTH-1); Sb.            Append ("},"); Return SB.        ToString (); }///<summary>///array to JSON///</summary>//<param name= "STRs" ></param            >//<returns></returns> public static string Arraytojson (string[] strs) {            StringBuilder sb = new StringBuilder (); for (int i = 0; i < STRs. Length; i++) {sb. AppEndformat ("' {0} ': ' {1} ',", i + 1, strs[i]); } if (sb. Length > 0) return "{" + sb. ToString ().            TrimEnd (', ') + "}";        Return ""; } #region Listtojson//<summary>//List convert JSON format///</summary>//&lt ;p Aram Name= "Jsonname" > class name </param>//<param name= "Objlist" >list collection </param>//<retu            rns></returns> public static string listtojson<t> (List<t> objlist, string jsonname) {            String result = "{"; If there is no name for the given class, specify an if (Jsonname.equals (string).                Empty) {Object o = objlist[0]; Jsonname = O.gettype ().            ToString ();            } result + = "\" "+ Jsonname +" \ ": [";            Processing the first line preceded by "," the number bool Firstline = true; foreach (Object oo in objlist) {if (!firstline) {resUlt = result + "," + Objecttojson (OO);                    } else {result = result + Objecttojson (oo) + "";                Firstline = false;        }} return result + "]}"; }///<summary>///single object conversion JSON///</summary>//<param name= "O" > Object </par            am>//<returns></returns> private static string Objecttojson (object o) {            String result = "{";            list<string> ls_propertys = new list<string> ();            Ls_propertys = Getobjectproperty (o); foreach (String str_property in Ls_propertys) {if (result.                Equals ("{")) {result = result + Str_property;                } else {result = result + "," + Str_property + ""; }} return result + "}";       }///<summary>///Get Object Properties///</summary>//<param name= "O" > Object </        param>//<returns></returns> private static list<string> Getobjectproperty (object o)            {list<string> propertyslist = new list<string> (); propertyinfo[] Propertys = O.gettype ().            GetProperties (); foreach (PropertyInfo p in propertys) {propertyslist.            ADD ("\" "+ p.name.tostring () +" \ ": \" "+ p.getvalue (o, null) +" \ "");        } return propertyslist; } #endregion public static string Hashtabletojson (Hashtable data, string dtname) {STRINGB            Uilder sb = new StringBuilder (); Sb.            Append ("{\" "); Sb.            Append (Dtname); Sb.            Append ("\": [{"); foreach (object key in data.                Keys) {Object value = Data[key]; Sb.                Append ("\" "); Sb.Append (key); Sb.                Append ("\": \ ""); if (! String.IsNullOrEmpty (value. ToString ()) && value! = DBNull.Value) {sb. Append (value).                Replace ("\ \", "/"); } else {sb.                Append (""); } sb.            Append ("\", "); } SB = sb. Remove (sb.)            Length-1, 1); Sb.            Append ("}]}"); Return Jsoncharfilter (sb.)        ToString ()); }///<summary>///JSON character filter///</summary>//<param name= "Sourcestr" &G t; The source string to filter </param>////<returns> returns the filtered string </returns> private static string Jsoncharfilte        R (String sourcestr) {return sourcestr; }    }}

Convert JSON format helper class

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.