Jsontools

Source: Internet
Author: User

Label:creation   with   tin   stringbu   run    obj    data    tools   cep   

    public class Jsontools {//<summary>//Generate Json string from the object///&LT ;/summary>//<param name= "obj" >Object</param>///<returns>json String</returns&gt        ; public static string Objecttojson (Object obj) {//system.runtime.serialization.json.datacontractjsonseri            Alizer; DataContractJsonSerializer serializer = new DataContractJsonSerializer (obj.            GetType ());            MemoryStream stream = new MemoryStream (); Serializer.            WriteObject (stream, obj); byte[] databytes = new Byte[stream.            Length]; Stream.            Position = 0; Stream. Read (databytes, 0, (int) stream.            Length);            String datastring = Encoding.UTF8.GetString (databytes);        return datastring; }///<summary>//Generate A object from Json string///</summary>//<para M name= "jsonstring" >json string</param> <param name= "obj" >Object</param>///<returns>Object</returns> public static obj ECT Jsontoobject (string jsonstring, Object obj) {DataContractJsonSerializer serializer = new Datacontra Ctjsonserializer (obj.            GetType ());            MemoryStream mstream = new MemoryStream (Encoding.UTF8.GetBytes (jsonstring)); obj = serializer.            ReadObject (Mstream);        return obj; }///<summary>//Generate A object from Json string///</summary>//<para M name= "jsonstring" >json string</param>//<param name= "obj" >Object</param>///<re turns>object</returns> public static T jsontoobject<t> (String jsonstring) {DataCo            Ntractjsonserializer serializer = new DataContractJsonSerializer (typeof (T));          using (MemoryStream mstream = new MemoryStream (Encoding.UTF8.GetBytes (jsonstring)))  {return (T) serializer.            ReadObject (Mstream);        }}///<summary> serialized data as JSON data format.         </summary>//<param name= "Value" > Serialized objects </param>///<returns></returns>        public static string ObjectToJson2 (object value) {return ObjectToJson2 (value, false);        }//<summary>///serialization data is in JSON data format. </summary>//<param name= "Value" > Serialized object </param>//<param name= "Clearlastzero" & gt; Do you want to clear 0</param>//<returns></returns> public static string ObjectToJson2 (object va) after the decimal place Lue, bool Clearlastzero) {Type type = value.            GetType ();            Newtonsoft.Json.JsonSerializer Json = new Newtonsoft.Json.JsonSerializer (); Json.            nullvaluehandling = Nullvaluehandling.ignore; Json. objectcreationhandling = Newtonsoft.Json.ObjectCreationHandling.RePlace Json.            missingmemberhandling = Newtonsoft.Json.MissingMemberHandling.Ignore; Json.                                    referenceloophandling = Referenceloophandling.ignore; Json.            Converters.add (New Newtonsoft.Json.Converters.StringEnumConverter ());            Isodatetimeconverter timeformate = new Isodatetimeconverter ();            Timeformate.datetimeformat = "YYYY-MM-DD"; Json.                    Converters.add (timeformate); Json.            formatting = formatting.indented; Json.                       nullvaluehandling = Nullvaluehandling.ignore; if (Clearlastzero) JSON.            Converters.add (New Minifiednumarrayconverter ());            StringWriter SW = new StringWriter ();            Newtonsoft.Json.JsonTextWriter writer = new JsonTextWriter (SW); Writer.            formatting = Formatting.none; Writer.            QuoteChar = ' "'; Writer.            QuoteName = false; Json.            Serialize (writer, value); string output =Sw.            ToString (); Writer.            Close (); Sw.            Close ();        return output; }///<summary>///Convert JSON data to object///</summary>//<typeparam name= "T" > Target object & lt;/typeparam>//<param name= "Jsontext" >json Data strings </param>///&LT;RETURNS&GT;&LT;/RETURNS&G        T public static T jsontoobject2<t> (String jsontext) {Newtonsoft.Json.JsonSerializer Json = new NEWT Onsoft.            Json.jsonserializer (); Json.            nullvaluehandling = Newtonsoft.Json.NullValueHandling.Ignore; Json.            objectcreationhandling = Newtonsoft.Json.ObjectCreationHandling.Replace; Json.            missingmemberhandling = Newtonsoft.Json.MissingMemberHandling.Ignore; Json.            referenceloophandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;            StringReader sr = new StringReader (jsontext);            Newtonsoft.Json.JsonTextReader reader = new JsonTextReader (SR); T result = defAult (T); try {result = (T) JSON.            Deserialize (reader, typeof (T)); } catch {} finally {reader.            Close ();        } return result; }///<summary>//General collection conversion JSON///</summary>//<param name= "Array" > Collection Object &L        t;/param>//<returns>json strings </returns> public static string Listtojson (IEnumerable array)            {String jsonstring = "[";            foreach (object item in array) {jsonstring + = Objecttojson (item) + ",";            } int t = Jsonstring.lastindexof (', ');            String strtmp = jsonstring.substring (0, T);        return strtmp + "]"; }///<summary>//DataTable to JSON///</summary>//<param name= " Jsonname "> returns the name of the JSON </param>//<paraM name= "DT" > Convert to JSON table </param>//<returns></returns> public string Datatabletojs On (string jsonname, System.Data.DataTable dt, string strtotal = "") {StringBuilder Json = new Stringbui            Lder ();            Json.append ("[{\" totalcount\ ": \" "+ strtotal +" \ ", \" head\ ": ["); for (int i = 0; i < dt. Columns.count; i++) {json.append ("{\" columnhead\ ": \" "+ dt + dt. Columns[i].                ColumnName + "\"} "); if (i < dt.                columns.count-1) {json.append (",");            }} json.append ("],");            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 (); } public class Minifiednumarrayconverter:jsonconverter {private void dumpnumarray<t> (Jso Nwriter writer, t[] array) {foreach (T n in array) {var s =                    N.tostring (); This allows you to use String.Format ("{0: #0. # # # #}") [small number of back # numbers determined by the maximum number of decimal digits]//Thanks to the Web friend Vencin for providing advice if (S.ENDSW ITH (". 0")) writer. Writerawvalue (s.substring (0, s.length-2));                    else if (S.contains (".")) Writer.                    Writerawvalue (S.trimend (' 0 ')); else writer.                Writerawvalue (s); }} private void Dumpnum<t> (Jsonwriter writer, T value) {var s = va Lue.                ToString (); This allows you to switch to String.Format ("{0: #0. # # # #}") [The decimal number is determined by the maximum number of decimal digits]//Thanks to the Web friend Vencin to provide advice if (S.endswith (". 0") )) writer.                Writerawvalue (s.substring (0, s.length-2));                    else if (S.contains (".")) Writer.                Writerawvalue (S.trimend (' 0 ')); else writer.            Writerawvalue (s);                } public override void Writejson (Jsonwriter writer, object value, Jsonserializer serializer) { Type T = value.                GetType (); if (t = = Dblarraytype) {writer.                    Writestartarray (); DumpnumArray<double> (writer, (double[]) value); Writer.                Writeendarray (); } else if (t = = Decarraytype) {writer.                    Writestartarray ();                    Dumpnumarray<decimal> (writer, (decimal[]) value); Writer.                Writeendarray (); } else if (t = = Dectype | | t = = decnulltype) {dumpnum<decimal> (WRI                ter, (decimal) value);            } else throw new NotImplementedException ();            } private Type Dblarraytype = typeof (double[]);            Private Type Decarraytype = typeof (decimal[]);            Private Type Dectype = typeof (decimal);            Private Type Decnulltype = typeof (decimal?); public override bool Canconvert (Type objectType) {if (ObjectType = = Dblarraytype | | objectType = = Decarraytype | | ObjectType = = Dectype | | ObjecttyPE = = Decnulltype) return true;            return false;            } public override bool CanRead {get {return false;} } public override Object Readjson (Jsonreader reader, Type objectType, Object Existingvalue, Jsonserializer Seri            Alizer) {throw new NotImplementedException (); }        }    }

  

Jsontools

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.

Tags Index: