本示例演示如何使用自定义 SyndicationFeedFormatter 和 DataContractJsonSerializer 来序列化 JavaScript 对象符号 (JSON) 格式的 SyndicationFeed 类的实例。
提示
此示例需要安装 .NET Framework 3.5 版才能生成和运行。若要打开项目和解决方案文件,需要使用 Visual Studio 2008。
示例的体系结构
本示例实现一个从 SyndicationFeedFormatter 继承的名为 JsonFeedFormatter
的类。JsonFeedFormatter
类依靠 DataContractJsonSerializer 来读写 JSON 格式的数据。在内部,格式化程序使用名为 JsonSyndicationFeed
和 JsonSyndicationItem
的一组自定义数据协定类型来控制由序列化程序生成的 JSON 数据的格式。对于最终用户,这些实现的详细信息是不可见的,从而可以针对标准 SyndicationFeed 和 SyndicationItem 类进行调用。
编写 JSON 源
通过与 DataContractJsonSerializer 一起使用 JsonFeedFormatter
(在本示例中实现),可实现编写 JSON 源,如下面的示例代码所示。
//Basic feed with sample data
SyndicationFeed feed = new SyndicationFeed("Custom JSON feed", "A Syndication extensibility sample", null);
feed.LastUpdatedTime = DateTime.Now;
feed.Items = from s in new string[] { "hello", "world" }
select new SyndicationItem()
{
Summary = SyndicationContent.CreatePlaintextContent(s)
};
//Write the feed out to a MemoryStream in JSON format
DataContractJsonSerializer writeSerializer = new DataContractJsonSerializer(typeof(JsonFeedFormatter));
writeSerializer.WriteObject(stream, new JsonFeedFormatter(feed));
读取 JSON 源
使用 JsonFeedFormatter
可以实现从 JSON 格式的数据流中获取 SyndicationFeed,如下面的代码所示。
//Read in the feed using the DataContractJsonSerializer
DataContractJsonSerializer readSerializer = new DataContractJsonSerializer(typeof(JsonFeedFormatter));
JsonFeedFormatter formatter = readSerializer.ReadObject(stream) as JsonFeedFormatter;
SyndicationFeed feedRead = formatter.Feed;
设置、生成和运行示例
若要生成 C# 或 Visual Basic .NET 版本的解决方案,请按照生成 Windows Communication Foundation 示例中的说明进行操作。
若要用单机配置或跨计算机配置来运行示例,请按照运行 Windows Communication Foundation 示例中的说明进行操作。
Send comments about this topic to Microsoft.
© 2007 Microsoft Corporation. All rights reserved.