JSON序列化与反序列化

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     }
View Code

2.创建web服务页面,进行序列化,并发布到本地服务器,我本地发布后的地址为:

http://localhost:8012/ceshi/WebService1.asmx?op=HaiHai

 1   public class Person
 2         {
 3             public string Name { get; set; }
 4 
 5             public int Age { get; set; }
 6         }
 7 
 8         [WebMethod]
 9         public string HaiHai()
10         {
11             Person person = new Person();
12             person.Name = "jack";
13             person.Age =26;
14             string jsonstring = JsonHelper.JsonSerializer<Person>(person);
15         
16             return jsonstring;
17            
18         }
View Code

 

3.将接口发布到本地IIS,然后根据接口的地址,获取数据反序列化

1  using (WebService1SoapClient client = new WebService1SoapClient())
2             {
3                 string ss = client.HaiHai();
4                 Response.Write(ss);
5                // context.Response.Write(ss);
6             } 
View Code

 

posted @ 2015-05-14 11:02  Jbp  阅读(236)  评论(0编辑  收藏  举报