源格式化程序 (JSON)

JsonFeeds 示例演示如何使用自定义 SyndicationFeedSyndicationFeedFormatter 以 JavaScript 对象表示法(JSON)格式序列化 DataContractJsonSerializer 类的一个实例。

示例的体系结构

此示例实现一个名为 JsonFeedFormatter 继承自 SyndicationFeedFormatter. 的类。 该 JsonFeedFormatter 类依赖于 DataContractJsonSerializer 以 JSON 格式读取和写入数据。 在内部,格式化程序使用一组命名 JsonSyndicationFeedJsonSyndicationItem 控制序列化程序生成的 JSON 数据的格式的自定义数据协定类型。 这些实现详细信息对最终用户而言是隐藏的,允许对标准类SyndicationFeedSyndicationItem进行调用。

编写 JSON 数据流

通过与 JsonFeedFormatter 一起使用 DataContractJsonSerializer(在本示例中实现),可实现编写 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 源

可以使用SyndicationFeed从 JSON 格式的数据流中获取JsonFeedFormatter,如以下代码所示。

//Read in the feed using the DataContractJsonSerializer

DataContractJsonSerializer readSerializer = new DataContractJsonSerializer(typeof(JsonFeedFormatter));

JsonFeedFormatter formatter = readSerializer.ReadObject(stream) as JsonFeedFormatter;

SyndicationFeed feedRead = formatter.Feed;

设置、生成和运行示例

  1. 确保已为 Windows Communication Foundation 示例 执行One-Time 安装过程。

  2. 若要生成解决方案的 C# 或 Visual Basic .NET 版本,请按照 生成 Windows Communication Foundation 示例中的说明进行操作。

  3. 若要在单台计算机或跨计算机配置中运行示例,请按照 运行 Windows Communication Foundation 示例中的说明进行操作。