Json数据是一种轻量级的数据交换格式,它的传输效率比XML更高,在Silverlight的应用起来可以让Silverlight获取数据速度增 快,减少传输的字符数量。在本节将用一个实例来讲解如何将一个类序列化为Json数据并且传输到Silverlight端。
实现原理:在服务器端新建一个一般处理程序页面“GetJson.ashx”,使用DataContractJsonSerializer类的 WriteObject()函数来将类序列化为Json数据集合,然后再Silverlight端通过 DataContractJsonSerializer类的ReadObject()函数来将Json数据还原为类。当然在Silverlight端我们 使用WebRequest来下载数据。
首先我们新建一个新的Silverlight应用程序,然后再服务器端和Silverlight端同时添加两个类City.cs(有数个属性)和Citys.cs(有一个属性为City类的List集合)。
- public class City
- {
- private string _CityName;
- private string _CityNum;
- private string _Provence;
- public string Provence
- {
- get { return _Provence; }
- set { _Provence = value; }
- }
- public string CityNum
- {
- get { return _CityNum; }
- set { _CityNum = value; }
- }
- public string CityName
- {
- get { return _CityName; }
- set { _CityName = value; }
- }
- }
- public class Citys
- {
- private List<City> _CityList;
- public List<City> CityList
- {
- get { return _CityList; }
- set { _CityList = value; }
- }
- }
然后我们在服务器端新建一个一般处理程序页面“GetJson.ashx”,然后添加以下代码以实例化多个城市对象,然后转回为Json数据。注意在这里我们需要单独引入System.Runtime.Serialization.dll;
- /// <summary>
- /// GetJson 的摘要说明
- /// </summary>
- public class GetJson : IHttpHandler
- {
- public void ProcessRequest(HttpContext context)
- {
- //步骤一
- //将类Citys格式化为Json字符串
- string JsonString = ToJsonString(GetCitys());
- context.Response.ContentType = "text/plain";
- context.Response.Write(JsonString);
- }
- private Citys GetCitys()
- {
- //实例化字符数据组
- Citys citys = new Citys();
- citys.CityList = new List<City>() {
- new City(){ CityName="成都", CityNum="028", Provence="四川"},
- new City(){ CityName="昆明", CityNum="028", Provence="云南"},
- new City(){ CityName="广州", CityNum="028", Provence="广东"},
- new City(){ CityName="上海", CityNum="028", Provence="上海"},
- new City(){ CityName="重庆", CityNum="028", Provence="重庆"}
- };
- return citys;
- }
- // 将一个Object类序列化为Json字符串
- public string ToJsonString(object ToJsonObject)
- {
- using (MemoryStream ms = new MemoryStream())
- {
- DataContractJsonSerializer serializer =
- new DataContractJsonSerializer(ToJsonObject.GetType());
- serializer.WriteObject(ms, ToJsonObject);
- StringBuilder sb = new StringBuilder();
- sb.Append(Encoding.UTF8.GetString(ms.ToArray()));
- return sb.ToString();
- }
- }
- public bool IsReusable
- {
- get
- {
- return false;
- }
- }
- }
运行GetJson.ashx页面我们可以得到类格式化为Json之后的字符如下:
- {"CityList":[{"CityName":"成都","CityNum":"028","Provence":"四川"},
- {"CityName":"昆明","CityNum":"028","Provence":"云南"},
- {"CityName":"广州","CityNum":"028","Provence":"广东"},
- {"CityName":"上海","CityNum":"028","Provence":"上海"},
- {"CityName":"重庆","CityNum":"028","Provence":"重庆"}]}
在Silverlight端首先需要引入System.ServiceModel.Web.dll和System.Runtime.Serialization.dll,然后再敲入下面代码以调用一般应用程序页面得到的字符串,并且反序列化为类。
- public MainPage()
- {
- InitializeComponent();
- //步骤二
- //调用http://localhost:2598/GetJson.ashx获取到Json数据流
- Uri endpoint = new Uri("http://localhost:2598/GetJson.ashx");
- WebRequest request = WebRequest.Create(endpoint);
- request.Method = "POST";
- request.ContentType = "application/x-www-form-urlencoded";
- request.BeginGetResponse(new AsyncCallback(ResponseReady), request);
- }
- void ResponseReady(IAsyncResult asyncResult)
- {
- WebRequest request = asyncResult.AsyncState as WebRequest;
- WebResponse response = request.EndGetResponse(asyncResult);
- //步骤三
- //调用UI线程更新DataGrid
- this.dataGrid1.Dispatcher.BeginInvoke(()=>{
- this.dataGrid1.ItemsSource =
- (Deserialize<Citys>(response.GetResponseStream()) as Citys).CityList;
- });
- }
- // 将Json字符流反序列化为对象
- public static T Deserialize<T>(Stream stream)
- {
- DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
- return (T)serializer.ReadObject(stream);
- }
本实例采用VS2010+Silverlight 4.0,如需源码请点击 SLLinkJson.rar 下载。
本文转自程兴亮 51CTO博客,原文链接:http://blog.51cto.com/chengxingliang/822727