码迷,mamicode.com
首页 > Web开发 > 详细

JSON序列化与反序列化

时间:2015-05-14 11:54:47      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:

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

 

JSON序列化与反序列化

标签:

原文地址:http://www.cnblogs.com/jbps/p/4502783.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!