json序列化和反序列化幫助類:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.Serialization; using System.Runtime.Serialization.Json; using System.IO; using System.Text.RegularExpressions; using System.Web.Script.Serialization; namespace HelpClass.TypeHelp { /// <summary> /// 在VS中需要添加引用System.Web.Script.Serialization的時候,請先引用System.Web.Extensions /// </summary> public class JsonHelp { /// <summary> /// json序列化(非二進制方式) /// </summary> /// <typeparam name="T"></typeparam> /// <param name="t"></param> /// <returns></returns> public static string JsonSerializer<T>(T t) { JavaScriptSerializer jsonSerialize = new JavaScriptSerializer(); return jsonSerialize.Serialize(t); } /// <summary> /// json反序列化(非二進制方式) /// </summary> /// <typeparam name="T"></typeparam> /// <param name="jsonString"></param> /// <returns></returns> public static T JsonDeserialize<T>(string jsonString) { JavaScriptSerializer jsonSerialize = new JavaScriptSerializer(); return (T)jsonSerialize.Deserialize<T>(jsonString); } /// <summary> /// JSON序列化(二進制方式,實體類使用[Serializable]) /// </summary> /// <typeparam name="T"></typeparam> /// <param name="t"></param> /// <returns></returns> public static string JsonSerializerIO<T>(T t) { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); using (MemoryStream ms = new MemoryStream()) { ser.WriteObject(ms, t); string jsonString = Encoding.UTF8.GetString(ms.ToArray()); ms.Close(); return jsonString; } } /// <summary> /// JSON反序列化(二進制方法,實體類使用[Serializable]) /// </summary> /// <typeparam name="T"></typeparam> /// <param name="jsonString"></param> /// <returns></returns> public static T JsonDeserializeIO<T>(string jsonString) { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString))) { T obj = (T)ser.ReadObject(ms); return obj; } } } }
上面這個類使用了兩中json序列化形式。
1、 使用System.Web.Script.Serialization進行序列化和反序列化,不過在VS中需要添加引用System.Web.Script.Serialization的時候,請先引用System.Web.Extensions。