1 #region model<->json(对象和json互转) 2 #region DataContractJsonSerializer 3 public static string SerializeDataContractJson<T>(T obj) 4 { 5 DataContractJsonSerializer json = new DataContractJsonSerializer(obj.GetType()); 6 using (MemoryStream stream = new MemoryStream()) 7 { 8 json.WriteObject(stream, obj); 9 string szJson = Encoding.UTF8.GetString(stream.ToArray()); 10 return szJson; 11 } 12 } 13 public static T DeserializeDataContractJson<T>(string szJson) 14 { 15 T obj = Activator.CreateInstance<T>(); 16 using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson))) 17 { 18 DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType()); 19 return (T)serializer.ReadObject(ms); 20 } 21 } 22 #endregion 23 24 #region Newtonsoft 25 static public string SerializeJSON<T>(T data) 26 { 27 return Newtonsoft.Json.JsonConvert.SerializeObject(data); 28 } 29 static public T DeserializeJSON<T>(string json) 30 { 31 return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(json); 32 } 33 #endregion 34 #endregion 35 36 #region datatable<->json(datatable和json互转) 37 public static string SerializeDataTableToJSON(DataTable dt) 38 { 39 return Newtonsoft.Json.JsonConvert.SerializeObject(dt); 40 } 41 public static DataTable SerializeJSONToDataTable(string json) 42 { 43 return Newtonsoft.Json.JsonConvert.DeserializeObject<DataTable>(json); 44 } 45 85 #endregion