Public Static Class Jsonhelper { /// <Summary> /// JSON serialization /// </Summary> Public Static String Jsonserializer <t> (T ){ // So Datacontractjsonserializer SER = New Datacontractjsonserializer ( Typeof Memorystream MS = New Memorystream (); Ser. writeobject (MS, t ); String Jsonstring = Encoding. utf8.getstring (Ms. toarray (); Ms. Close (); // Replace the JSON date string Const String P =@" \/Date \ (\ D +) \ + \ D + \)\\/ " ; Matchevaluator = Convertjsondatetodatestring; RegEx Reg = New RegEx (p); jsonstring = Reg. Replace (jsonstring, matchevaluator ); Return Jsonstring ;} /// <Summary> /// Generate a JSON string from an object /// </Summary> /// <Param name = "OBJ"> Conversion object </Param> /// <Typeparam name = "T"> Object Type </Typeparam> /// <Returns> </returns> Public Static String Tojson <t> ( This T OBJ ){ VaR Fullname = Typeof (T). fullname; If (Fullname! = Null & Fullname. Contains ( " <> F _ anonymoustype " )){ // Anonymous type VaR Serializer = New System. Web. Script. serialization. javascriptserializer (); Return Serializer. serialize (OBJ );} Else { VaR Serializer = New Datacontractjsonserializer ( Typeof (T )); String JSON; Using (Memorystream stream = New Memorystream () {serializer. writeobject (stream, OBJ); JSON = Encoding. utf8.getstring (stream. toarray (); stream. Close ();} Return JSON ;}} /// <Summary> /// JSON deserialization /// </Summary> Public Static T jsondeserialize <t> ( String Jsonstring ){ // Convert a string in the format of "yyyy-mm-dd hh: mm: SS" to "\/date (1294499956278 + 0800) \/". Const String P = @" \ D {4}-\ D {2}-\ D {2} \ s \ D {2 }:\ d {2 }:\ d {2} " ; Matchevaluator = Convertdatestringtojsondate; RegEx Reg = New RegEx (p); jsonstring = Reg. Replace (jsonstring, matchevaluator); datacontractjsonserializer Ser = New Datacontractjsonserializer ( Typeof Memorystream MS = New Memorystream (encoding. utf8.getbytes (jsonstring); t OBJ = (T) SER. readobject (MS ); Return OBJ ;} /// <Summary> /// Converts the JSON serialization time from/date (1294499956278 + 0800) to a string. /// </Summary> Private Static String Convertjsondatetodatestring (Match m) {datetime dt = New Datetime ( 1970 , 1 , 1 ); Dt = DT. addmilliseconds ( Long . Parse (M. Groups [ 1 ]. Value); dt = DT. tolocaltime (); String Result = DT. tostring ( " Yyyy-mm-dd hh: mm: SS " ); Return Result ;} /// <Summary> /// Convert the time string to JSON time /// </Summary> Private Static String Convertdatestringtojsondate (Match m) {datetime dt = Datetime. parse (M. Groups [ 0 ]. Value); dt = DT. touniversaltime (); timespan TS = DT-datetime. parse ( " 1970-01-01 " ); String Result = String . Format ( " \\/ Date ({0} + 0800 )\\/ " , Ts. totalmilliseconds ); Return Result ;}}
Original address http://blog.csdn.net/allsharps/article/details/7357446