[源码下载]
稳扎稳打Silverlight(19) - 2.0通信之调用REST服务,处理JsON格式,XML格式,RSS/ATOM格式的数据
作者: webabcd
介绍
Silverlight 2.0 调用REST服务,处理JsON格式,RSS/ATOM格式的数据
通过 System.Net.WebClIEnt 类调用 REST 服务
通过 System.Json 命名控件下的类处理 JsON 数据
通过 System.Xml.linq 命名空间下的类(liNQ to XML)处理 XML 数据
通过 System.ServiceModel.Syndication 命名空间下的类处理 RSS/ATOM 数据
在线DEMO
http://www.cnblogs.com/webabcd/archive/2008/10/09/1307486.html
示例
1、调用 REST 服务,返回 JsON 数据
REST.cs(WCF创建的REST服务)
using System;
using System.linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Collections.Generic;
using System.Text;
using System.IO;
/**/ /// <summary>
/// 提供 REST 服务的类
/// 注:Silverlight只支持 GET 和 POST
/// </summary>
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class REST
{
/**//// <summary>
/// 用于演示返回 JsON(对象) 的 REST 服务
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
[OperationContract]
[WebGet(UriTemplate = "User/{name}/Json", ResponseFormat = Webmessageformat.Json)]
public User HelloJson(string name)
{
return new User { name = name, DayOfBirth = new DateTime(1980, 2, 14) };
}
@H_502_385@/**//// <summary>
/// 用于演示返回 JsON(集合) 的 REST 服务
/// </summary>
/// <returns></returns>
[OperationContract]
[WebGet(UriTemplate = "Users/Json", ResponseFormat = Webmessageformat.Json)]
public List<User> HelloJson2()
{
return new List<User>
{
new User(){ name = "webabcd01", 1, 1) },
new User(){ name = "webabcd02", 2) },
new User(){ name = "webabcd03", 3, 3) },
};
}
}
Json.xaml
< UserControl x:Class ="Silverlight20.Communication.Json"
xmlns ="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x ="http://schemas.microsoft.com/winfx/2006/xaml" >
< StackPanel HorizontalAlignment ="left" WIDth ="600" >
< TextBox x:name ="txtMsgJson" margin ="5" />
< TextBox x:name ="txtMsgJson2" margin ="5" />
</ StackPanel >
</ UserControl >
Json.xaml.cs
using System;
using System.Collections.Generic;
using System.linq;
using System.Net;
using System.windows;
using System.windows.Controls;
using System.windows.documents;
using System.windows.input;
using System.windows.Media;
using System.windows.Media.Animation;
using System.windows.Shapes;
using System.IO;
namespace Silverlight20.Communication
{
public partial class Json : UserControl
{
public Json()
{
InitializeComponent();
// 演示如何处理 JsON(对象)
JsonDemo();
// 演示如何处理 JsON(集合)
JsonDemo2();
}
/**//// <summary>
/// 演示如何处理 JsON(对象)
/// </summary>
voID JsonDemo()
{
// REST 服务的 URL
Uri uri = new Uri("http://localhost:3036/REST.svc/User/webabcd/Json", UriKind.absolute);
// 实例化 WebClIEnt
System.Net.WebClIEnt clIEnt = new System.Net.WebClIEnt();
clIEnt.DownloadStringCompleted += new DownloadStringCompletedEventHandler(Json_DownloadStringCompleted);
clIEnt.DownloadStringAsync(uri);
txtMsgJson.Text = "读取 JsON(对象) 数据中。。。";
}
voID Json_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
{
// 发生错误的话,则打印出来
txtMsgJson.Text = e.Error.ToString();
return;
}
// 将获得的字符串转换为 JsON(对象)
var buffer = System.Text.EnCoding.UTF8.GetBytes(e.Result);
var ms = new MemoryStream(buffer);
var JsonObject = System.Json.JsonObject.Load(ms) as System.Json.JsonObject;
txtMsgJson.Text = e.Result + "/r/n";
// 解析 JsON(对象)
txtMsgJson.Text += string.Format("姓名: {0}, 生日: {1}",
(string)JsonObject["name"],
((DateTime)JsonObject["DayOfBirth"]).ToString("yyyy-MM-dd"));
/**//*
* 总结:
* JsonObject - 一个具有零或多个 key-value 对的无序集合。继承自抽象类 JsonValue
* JsonObject.Load(Stream) - 将指定的字符串流反序列化为 JsON 对象(CLR可用的类型)
* JsonObject[key] - JsonObject 索引器,获取 JsonObject 的指定key的value
* JsonObject.ContainsKey(key) - JsonObject 对象内是否具有指定的key
*/
}
/**//// <summary>
/// 演示如何处理 JsON(集合)
/// </summary>
voID JsonDemo2()
{
// REST 服务的 URL
Uri uri = new Uri("http://localhost:3036/REST.svc/Users/Json", UriKind.absolute);
// 实例化 WebClIEnt
System.Net.WebClIEnt clIEnt = new System.Net.WebClIEnt();
clIEnt.DownloadStringCompleted += new DownloadStringCompletedEventHandler(Json2_DownloadStringCompleted);
clIEnt.DownloadStringAsync(uri);
txtMsgJson2.Text = "读取 JsON(集合) 数据中。。。";
}
voID Json2_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
{
// 发生错误的话,则打印出来
txtMsgJson2.Text = e.Error.ToString();
return;
}
// 将获得的字符串转换为 JsON(集合)
var buffer = System.Text.EnCoding.UTF8.GetBytes(e.Result);
var ms = new MemoryStream(buffer);
var JsonArray = System.Json.JsonArray.Load(ms) as System.Json.JsonArray;
txtMsgJson2.Text = e.Result + "/r/n";
txtMsgJson2.Text += string.Format("姓名: {0},
(string)JsonArray.First()["name"],
((DateTime)JsonArray.Single(p => p["name"] == "webabcd02")["DayOfBirth"]).ToString("yyyy-MM-dd"));
/**//*
* 总结:
* JsonArray - 一个具有零或多个 JsonValue(抽象类,JsonObject和JsonArray都继承自此类) 对象的有序序列
* JsonArray.Load(Stream) - 将指定的字符串流反序列化为 JsON 对象(CLR可用的类型)
* JsonArray[index] - JsonArray 索引器,获取 JsonArray 的指定索引的 JsonValue
* JsonArray 支持 liNQ
*/
}
}
}
2、调用 REST 服务,返回 XML 数据
REST.cs(WCF创建的REST服务)
using System;
using System.linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Collections.Generic;
using System.Text;
using System.IO;
/**/ /// <summary>
/// 提供 REST 服务的类
/// 注:Silverlight只支持 GET 和 POST
/// </summary>
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class REST
{
/**//// <summary>
/// 用于演示返回 XML(对象) 的 REST 服务
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
[OperationContract]
[WebGet(UriTemplate = "User/{name}/xml", ResponseFormat = Webmessageformat.Xml)]
public User HelloXml(string name)
{
return new User { name = name, 14) };
}
/**//// <summary>
/// 用于演示返回 XML(集合) 的 REST 服务
/// </summary>
/// <returns></returns>
[OperationContract]
[WebGet(UriTemplate = "Users/xml", ResponseFormat = Webmessageformat.Xml)]
public List<User> HelloXml2()
{
return new List<User>
{
new User(){ name = "webabcd01",
new User(){ name = "webabcd02",
new User(){ name = "webabcd03",
};
}
}
Xml.xaml
< UserControl x:Class ="Silverlight20.Communication.Xml"
xmlns ="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x ="http://schemas.microsoft.com/winfx/2006/xaml" >
< StackPanel HorizontalAlignment ="left" WIDth ="600" >
< TextBox x:name ="txtMsgXml" margin ="5" />
< TextBox x:name ="txtMsgXml2" margin ="5" />
</ StackPanel >
</ UserControl >
Xml.xaml.cs
using System;
using System.Collections.Generic;
using System.linq;
using System.Net;
using System.windows;
using System.windows.Controls;
using System.windows.documents;
using System.windows.input;
using System.windows.Media;
using System.windows.Media.Animation;
using System.windows.Shapes;
using System.Xml.linq;
using System.IO;
namespace Silverlight20.Communication
{
public partial class Xml : UserControl
{
public Xml()
{
InitializeComponent();
// 演示如何处理 XML(对象)
XmlDemo();
// 演示如何处理 XML(集合)
XmlDemo2();
}
/**//// <summary>
/// 演示如何处理 XML(对象)
/// </summary>
voID XmlDemo()
{
// REST 服务的 URL
Uri uri = new Uri("http://localhost:3036/REST.svc/User/webabcd/xml", UriKind.absolute);
// 实例化 WebClIEnt
System.Net.WebClIEnt clIEnt = new System.Net.WebClIEnt();
clIEnt.DownloadStringCompleted += new DownloadStringCompletedEventHandler(xml_DownloadStringCompleted);
clIEnt.DownloadStringAsync(uri);
txtMsgXml.Text = "读取 XML(对象) 数据中。。。";
}
voID xml_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
{
// 发生错误的话,则打印出来
txtMsgXml.Text = e.Error.ToString();
return;
}
// 将获得的字符串转换为 XML(对象)
var buffer = System.Text.EnCoding.UTF8.GetBytes(e.Result);
var ms = new MemoryStream(buffer);
XElement xmlObject = XElement.Load(ms);
txtMsgXml.Text = e.Result + "/r/n";
Xnamespace ns = "http://webabcd.cnblogs.com/";
txtMsgXml.Text += string.Format("姓名: {0},
(string)xmlObject.Element(ns + "name"),
((DateTime)xmlObject.Element(ns + "DayOfBirth")).ToString("yyyy-MM-dd"));
/**//*
* 总结:
* XElement - 表示一个 XML 元素
* XElement.Element - XML 元素内的 XML 元素
* XElement.Attribute - XML 元素内的 XML 属性
* XElement.Load(Stream) - 使用指定流创建一个 XElement 对象
* XElement.Parse(String) - 解析指定的 XML 字符串为一个 XElement 对象
* XAttribute - 表示一个 XML 属性
*/
}
/**//// <summary>
/// 演示如何处理 XML(集合)
/// </summary>
voID XmlDemo2()
{
// REST 服务的 URL
Uri uri = new Uri("http://localhost:3036/REST.svc/Users/xml", UriKind.absolute);
// 实例化 WebClIEnt
System.Net.WebClIEnt clIEnt = new System.Net.WebClIEnt();
clIEnt.DownloadStringCompleted += new DownloadStringCompletedEventHandler(xml2_DownloadStringCompleted);
clIEnt.DownloadStringAsync(uri);
txtMsgXml2.Text = "读取 XML(集合) 数据中。。。";
}
voID xml2_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
{
// 发生错误的话,则打印出来
txtMsgXml2.Text = e.Error.ToString();
return;
}
// 将获得的字符串转换为 XML(集合)
Xdocument xmlObject = Xdocument.Parse(e.Result);
txtMsgXml2.Text = e.Result + "/r/n";
Xnamespace ns = "http://webabcd.cnblogs.com/";
var obj = from p in xmlObject.Elements(ns + "ArrayOfUser").Elements(ns + "User")
where p.Element(ns + "name").Value == "webabcd02"
select new { name = (string)p.Element(ns + "name"), DayOfBirth = (DateTime)p.Element(ns + "DayOfBirth") };
txtMsgXml2.Text += string.Format("姓名: {0},
obj.First().name,
obj.First().DayOfBirth.ToString("yyyy-MM-dd"));
/**//*
* 总结:
* liNQ to XML 相当的方便
*/
}
}
}
3、调用 REST 服务,返回 RSS/Atom 数据
Proxy.aspx.cs(返回指定的URL地址的内容的服务)
using System;
using System.Collections.Generic;
using System.linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Proxy : System.Web.UI.Page
{
protected voID Page_Load(object sender, EventArgs e)
{
// 获取某个 url 地址的 HTML 并在页面上输出
string url = Request.queryString["url"];
System.Net.WebClIEnt clIEnt = new System.Net.WebClIEnt();
clIEnt.EnCoding = System.Text.EnCoding.UTF8;
Response.Write(clIEnt.DownloadString(url));
Response.End();
}
}
RSSAtom.xaml
< UserControl x:Class ="Silverlight20.Communication.RSSAtom"
xmlns ="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x ="http://schemas.microsoft.com/winfx/2006/xaml" >
< StackPanel HorizontalAlignment ="left" >
< TextBox x:name ="txtMsgRSS" WIDth ="600" margin ="5" />
< StackPanel OrIEntation ="Horizontal" >
< ListBox x:name ="List" WIDth ="300" margin ="5" SelectionChanged ="List_SelectionChanged" >
< ListBox.ItemTemplate >
< DataTemplate >
< TextBlock Text =" {Binding Title.Text} " ></ TextBlock >
</ DataTemplate >
</ ListBox.ItemTemplate >
</ ListBox >
< TextBlock x:name ="detail" WIDth ="300" margin ="5" Text =" {Binding Summary.Text} " textwrapPing ="Wrap" />
</ StackPanel >
</ StackPanel >
</ UserControl >
RSSAtom.xaml.cs
using System;
using System.Collections.Generic;
using System.linq;
using System.Net;
using System.windows;
using System.windows.Controls;
using System.windows.documents;
using System.windows.input;
using System.windows.Media;
using System.windows.Media.Animation;
using System.windows.Shapes;
using System.Xml;
using System.IO;
using System.ServiceModel.Syndication;
namespace Silverlight20.Communication
{
public partial class RSSAtom : UserControl
{
public RSSAtom()
{
InitializeComponent();
// 演示如何处理 RSS/Atom
RSSDemo();
}
/**//// <summary>
/// 演示如何处理 RSS/Atom
/// </summary>
voID RSSDemo()
{
// 让一个代理页面去请求相关的 RSS/Atom(如果用Silverlight直接去请求,则需要在目标域的根目录下配置策略文件)
Uri uri = new Uri("http://localhost:3036/Proxy.aspx?url=http://webabcd.cnblogs.com/RSS", UriKind.absolute);
// 实例化 WebClIEnt
System.Net.WebClIEnt clIEnt = new System.Net.WebClIEnt();
clIEnt.DownloadStringCompleted += new DownloadStringCompletedEventHandler(RSS_DownloadStringCompleted);
clIEnt.DownloadStringAsync(uri);
txtMsgRSS.Text = "读取 RSS 数据中。。。";
}
voID RSS_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
{
// 发生错误的话,则打印出来
txtMsgRSS.Text = e.Error.ToString();
return;
}
// 将获得的字符串转换为 XmlReader
var buffer = System.Text.EnCoding.UTF8.GetBytes(e.Result);
var ms = new MemoryStream(buffer);
XmlReader reader = XmlReader.Create(ms);
// 从指定的 XmlReader 中加载,以生成 Syndication@R_403_6146@
Syndication@R_403_6146@ @R_403_6146@ = Syndication@R_403_6146@.Load(reader);
// 设置 List 的数据源为 RSS/Atom 的项集合(Syndication@R_403_6146@.Items)
List.ItemsSource = @R_403_6146@.Items;
txtMsgRSS.Text = e.Result + "/r/n";
}
private voID List_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// 设置 detail 的数据上下文为 RSS/Atom 的指定项(SyndicationItem)
detail.DataContext = List.SelectedItem as SyndicationItem;
}
}
}
OK
[源码下载] 总结
以上是内存溢出为你收集整理的稳扎稳打Silverlight(19) - 2.0通信之调用REST服务,处理JSON格式, XML格式, RSS/ATOM格式的数据全部内容,希望文章能够帮你解决稳扎稳打Silverlight(19) - 2.0通信之调用REST服务,处理JSON格式, XML格式, RSS/ATOM格式的数据所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)