このサンプルでは、カスタムの SyndicationFeedFormatter および DataContractJsonSerializer を使用することにより JSON (JavaScript Object Notation) 形式の SyndicationFeed クラスのインスタンスをシリアル化する方法を示します。
サンプルのアーキテクチャ
このサンプルは SyndicationFeedFormatter を継承する JsonFeedFormatter という名前のクラスを実行します。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;
サンプルを設定、ビルド、および実行するには
「Windows Communication Foundation サンプルの 1 回限りのセットアップの手順」が実行済みであることを確認します。
ソリューションの C# 版または Visual Basic .NET 版をビルドするには、「Windows Communication Foundation サンプルのビルド」の手順に従います。
単一コンピューター構成か複数コンピューター構成かに応じて、「Running the Windows Communication Foundation Samples」の手順に従います。
注 : |
|---|
サンプルは、既にコンピューターにインストールされている場合があります。続行する前に、次の (既定の) ディレクトリを確認してください。
<InstallDrive>:\WF_WCF_Samples
このディレクトリが存在しない場合は、「.NET Framework 4 向けの Windows Communication Foundation (WCF) および Windows Workflow Foundation (WF) のサンプル」にアクセスして、Windows Communication Foundation (WCF) および WF のサンプルをすべてダウンロードしてください。このサンプルは、次のディレクトリに格納されます。
<InstallDrive>:\WF_WCF_Samples\WCF\Extensibility\Syndication\JsonFeeds
|
注 :