次の方法で共有


フィード フォーマッタ (JSON)

JsonFeeds サンプルでは、カスタムの SyndicationFeedFormatter および DataContractJsonSerializer を使用することにより JSON (JavaScript Object Notation) 形式の SyndicationFeed クラスのインスタンスをシリアル化する方法を示します。

サンプルのアーキテクチャ

このサンプルは JsonFeedFormatter を継承する SyndicationFeedFormatter という名前のクラスを実行します。 JsonFeedFormatter クラスは DataContractJsonSerializer に依存し、JSON 形式でデータの読み取りと書き込みを行います。 内部的には、フォーマッタは JsonSyndicationFeed および JsonSyndicationItem という名前のデータ コントラクト型のカスタム セットを使用し、シリアライザによって生成される JSON データの形式を制御します。 これらの実装の詳細はエンド ユーザーには表示されず、標準的な SyndicationFeed および SyndicationItem クラスに対する呼び出しを行うことができます。

JSON フィードの書き込み

次のコード例に示すように、JSON フィードの書き込みは JsonFeedFormatter (このサンプルで実装) を DataContractJsonSerializer と共に使用して実行できます。

//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 フィードの読み取り

次のコードに示すように、JSON 形式のデータのストリームからの SyndicationFeed の取得は 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 サンプルの 1 回限りのセットアップの手順を実行したことを確認します。

  2. ソリューションの C# 版または Visual Basic .NET 版をビルドするには、「 Building the Windows Communication Foundation Samples」の手順に従います。

  3. 単一または複数コンピューター構成でサンプルを実行するには、「Windows Communication Foundation サンプルの実行」の手順に従います。