json序列化与反序列化
1 using System.Runtime.Serialization.Json; 2 3 /// <summary> 4 /// 将对象转化为Json字符串 5 /// </summary> 6 /// <typeparam name="T">源类型</typeparam> 7 /// <param name="obj">源类型实例</param> 8 /// <returns>Json字符串</returns> 9 public static string GetJsonFromObj<T>(T obj) 10 { 11 DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(obj.GetType()); 12 using (MemoryStream ms = new MemoryStream()) 13 { 14 jsonSerializer.WriteObject(ms, obj); 15 return Encoding.UTF8.GetString(ms.ToArray()); 16 } 17 } 18 19 /// <summary> 20 /// 将Json字符串转化为对象 21 /// </summary> 22 /// <typeparam name="T">目标类型</typeparam> 23 /// <param name="strJson">Json字符串</param> 24 /// <returns>目标类型的一个实例</returns> 25 public static T GetObjFromJson<T>(string strJson) 26 { 27 T obj = Activator.CreateInstance<T>(); 28 using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(strJson))) 29 { 30 DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(obj.GetType()); 31 return (T)jsonSerializer.ReadObject(ms); 32 } 33 }
ha666@ha666.com