DataContractJsonSerializer在System.Runtime.Serialization.Json命名空间下,.NET Framework 3.5包含在System.ServiceModel.Web.dll中,需要添加对其的引用;.NET Framework 4在System.Runtime.Serialization中。
1.创建 JsonHelper类
1 //JSON序列化和反序列化辅助类 2 public class JsonHelper 3 { 4 // JSON序列化 5 public static string JsonSerializer<T>(T t) 6 { 7 DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); 8 MemoryStream ms = new MemoryStream(); 9 ser.WriteObject(ms, t); 10 string jsonString = Encoding.UTF8.GetString(ms.ToArray()); 11 ms.Close(); 12 return jsonString; 13 } 14 15 //JSON反序列化 16 public static T JsonDeserialize<T>(string jsonString) 17 { 18 DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); 19 MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)); 20 T obj = (T)ser.ReadObject(ms); 21 return obj; 22 } 23 24 }