共用方式為


摘要格式器 (JSON)

JsonFeeds 範例會示範如何使用自訂 SyndicationFeedFormatterDataContractJsonSerializer,序列化採用 JavaScript 物件標記法 (JSON) 格式的 SyndicationFeed 類別執行個體。

範例架構

此範例會實作繼承自 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 範例的一次性安裝程序

  2. 若要建置方案的 C# 或 Visual Basic .NET 版本,請遵循 Building the Windows Communication Foundation Samples中的指示。

  3. 若要在單一或多部電腦組態中執行此範例,請遵循執行 Windows Communication Foundation 範例中的指示進行。