Public Static stringObj2json<t>(T data) {Try{System.Runtime.Serialization.Json.DataContractJsonSerializer Serializer=NewSystem.Runtime.Serialization.Json.DataContractJsonSerializer (data. GetType ()); using(MemoryStream ms =NewMemoryStream ()) {Serializer. WriteObject (MS, data); returnEncoding.UTF8.GetString (Ms. ToArray ()); } } Catch { return NULL; } }
Public StaticObject json2obj (String json,type t) {Try{System.Runtime.Serialization.Json.DataContractJsonSerializer Serializer=NewSystem.Runtime.Serialization.Json.DataContractJsonSerializer (t); using(MemoryStream ms =NewMemoryStream (Encoding.UTF8.GetBytes (JSON))) { returnSerializer. ReadObject (MS); } } Catch { return NULL; } }
Public Static stringDatatable2json (DataTable dt) {if(dt. Rows.Count = =0) { return ""; } StringBuilder Jsonbuilder=NewStringBuilder (); //Jsonbuilder.append ("{"); //jsonbuilder.append (dt. Tablename.tostring ()); Jsonbuilder.append ("[");//Convert to multiple model forms for(inti =0; i < dt. Rows.Count; i++) {jsonbuilder.append ("{"); for(intj =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 ("}"); returnjsonbuilder.tostring (); }
TList, DataTable to Json