主要用到的类:DataContractJsonSerializer,该类被申明在System.Runtime.Serialization.Json命名空间下,而System.Runtime.Serialization.Json命名空间是被放置在System.ServiceModel.Web.dll程序集里,因此我们要用到DataContractJsonSerializer类,首先应添加对System.ServiceModel.Web的引用,然后添加System.Runtime.Serialization.Json命名空间,注意DataContractJsonSerializer序列化的方式是采用数据契约序列化,因此我们可以通过DataMemberAttribute来控制那些被序列化,那些不被序列化。 例如,我们这里有一个类:
1 [DataContract] 2 public class User 3 { 4 public User() { } 5 [DataMember] 6 public bool IsMember { get ; set ; } 7 [DataMember] 8 public string Name { get ; set ; } 9 public int Age { get ; set ; } 10 }
我们现在在一个ashx文件里创建一个实例并将其序列化:
public class JsonWriter : IHttpHandler{ public void ProcessRequest (HttpContext context) { DataContractJsonSerializer serializer = new DataContractJsonSerializer( typeof (User)); User user = new User() { IsMember = true , Name = " Zhang Liang " , Age = 24 }; serializer.WriteObject(context.Response.OutputStream, user); context.Response.ContentType = " text/plain " ; } public bool IsReusable { get { return false ; } }}
看输出结果:
{ " IsMember " : true , " Name " : " Zhang Liang " }
反序列化:
public class JsonWriter : IHttpHandler{ public void ProcessRequest (HttpContext context) { DataContractJsonSerializer serializer = new DataContractJsonSerializer( typeof (User)); User user = serializer.ReadObject(context.Request.InputStream) as User; // .使用User对象 context.Response.Write( " OK " ); context.Response.ContentType = " text/plain " ; } public bool IsReusable { get { return false ; } }}