JsonFeeds サンプルは、カスタム SyndicationFeedとSyndicationFeedFormatterを使用して、DataContractJsonSerializer クラスのインスタンスを JavaScript Object Notation (JSON) 形式でシリアル化する方法を示しています。
サンプルのアーキテクチャ
このサンプルでは、JsonFeedFormatter
から継承する SyndicationFeedFormatter という名前のクラスを実装します。
JsonFeedFormatter
クラスは、JSON 形式でデータを読み書きするDataContractJsonSerializerに依存します。 内部的には、フォーマッタは、 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 サンプル のOne-Time セットアップ手順を実行していることを確認します。
ソリューションの C# または Visual Basic .NET エディションをビルドするには、「Windows Communication Foundation サンプルのビルド」の手順に従います。
単一または複数のコンピューター間の構成でサンプルを実行するには、「Windows Communication Foundation Samplesの実行」の手順に従います。