json序列化和发序列化
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Runtime.Serialization.Json; 6 using System.IO; 7 8 namespace Dtsc.WorkFlow 9 { 10 public class JsonHelper 11 { 12 public static object GetObjectListByJsonText(Type t,string jsonText) 13 { 14 object obj = null; 15 DataContractJsonSerializer ser1 = new DataContractJsonSerializer(t); 16 using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonText))) 17 { 18 obj = ser1.ReadObject(ms); 19 } 20 return obj; 21 } 22 23 /// <summary> 24 /// 返回序列化Json字符串 25 /// </summary> 26 /// <typeparam name="T"></typeparam> 27 /// <param name="TObject">需转换对象,注意:需转换对象必须标注[Serializable]特性,对象属性必须标注[Serializable]特性</param> 28 /// <returns></returns> 29 public static string GetJsonString<T>(T TObject) 30 { 31 DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T)); 32 using (MemoryStream ms = new MemoryStream()) 33 { 34 serializer.WriteObject(ms, TObject); 35 string ss = Encoding.UTF8.GetString(ms.GetBuffer()); 36 return ss.Replace("\0", ""); 37 } 38 } 39 40 /// <summary> 41 /// 将Json字符串转换成相应对象。 42 /// </summary> 43 /// <typeparam name="T"></typeparam> 44 /// <param name="json">Json字符串</param> 45 /// <returns></returns> 46 public static T ReturnJsonObject<T>(string json) 47 { 48 DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T)); 49 using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json))) 50 { 51 return (T)serializer.ReadObject(ms); 52 } 53 } 54 } 55 }