概述
Silverlight 2 Beta 1版本发布了,无论从Runtime还是Tools都给我们带来了很多的惊喜,如支持框架语言Visual Basic,Visual C#,IronRuby,Ironpython,对JSON、Web Service、WCF以及Sockets的支持等一系列新的特性。《一步一步学Silverlight 2系列》文章带您快速进入Silverlight 2开发。
本文将简单介绍在Silverlight 2中对于JSON的支持。
简单示例
public class Post { public int Id { get; set; } public string Title { get; set; } public string Author { get; set; } }
public class Blog { public List<Post> Posts { get; set; } }
在Silverlight项目中我们也会使用到这两个实体类,新建一个HttpHandler,产生JSON格式数据,我们使用Json.NET中的JavaScriptConvert.SerializeObject方法即可序列化一个对象为JSON格式:
public class BlogHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; List<Post> posts = new List<Post>() { new Post{ Id=1,Title="一步一步学Silverlight 2系列(13):数据与通信之WebRequest",Author="TerryLee" },new Post{ Id=2,Title="一步一步学Silverlight 2系列(12):数据与通信之WebClient",new Post{ Id=3,Title="一步一步学Silverlight 2系列(11):数据绑定",new Post{ Id=4,Title="一步一步学Silverlight 2系列(10):使用用户控件",new Post{ Id=5,Title="一步一步学Silverlight 2系列(9):使用控件模板",new Post{ Id=6,Title="一步一步学Silverlight 2系列(8):使用样式封装控件观感",Author="TerryLee" } }; Blog blog = new Blog(); blog.Posts = posts; context.Response.Write(JavaScriptConvert.SerializeObject(blog)); } public bool IsReusable { get { return false; } } }
现在测试一下HttpHandler,查看一下生成的数据格式:
对这些数据格式化一下,看起来更明显,这里推荐一个在线JSON数据格式化工具
[url]http://www.curiousconcept.com/jsonformatter/[/url]:
格式化后的数据如下:
现在实现在Silverlight中获取JSON数据,并进行反序列化,界面布局XAML就不再贴出来了,跟前面两篇的示例一样。在Silverlight 2中,内置了对于JSON的支持,通过命名空间System.Runtime.Serialization.Json提供,位于System.ServiceModel.Web.dll中。
我们使用WebRequest获取数据:
private void UserControl_Loaded(object sender,RoutedEventArgs e) { Uri endpoint = new Uri("http://localhost:8081/BlogHandler.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); using (Stream responseStream = response.GetResponseStream()) { DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(Blog)); Blog blog = jsonSerializer.Readobject(responseStream) as Blog; Posts.ItemsSource = blog.Posts; } }
结束语
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。