Export (0) Print
Expand All

Feed Formatter (JSON)

This sample shows how to serialize an instance of a SyndicationFeed class in JavaScript Object Notation (JSON) format by using a custom SyndicationFeedFormatter and the DataContractJsonSerializer.

The sample implements a class named JsonFeedFormatter that inherits from SyndicationFeedFormatter. The JsonFeedFormatter class relies on the DataContractJsonSerializer to read and write the data in JSON format. Internally, the formatter uses a custom set of data contract types named JsonSyndicationFeed and JsonSyndicationItem to control the format of the JSON data produced by the serializer. These implementation details are hidden from the end user, allowing calls to be made against the standard SyndicationFeed and SyndicationItem classes.

Writing a JSON feed can be accomplished by using the JsonFeedFormatter (implemented in this sample) with the DataContractJsonSerializer as shown in the following sample code.

//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));

Obtaining a SyndicationFeed from a stream of JSON-formatted data can be accomplished with the JsonFeedFormatter as show in the following code.

//Read in the feed using the DataContractJsonSerializer

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

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

SyndicationFeed feedRead = formatter.Feed;

To set up, build, and run the sample

  1. Ensure that you have performed the One-Time Setup Procedure for the Windows Communication Foundation Samples.

  2. To build the C# or Visual Basic .NET edition of the solution, follow the instructions in Building the Windows Communication Foundation Samples.

  3. To run the sample in a single- or cross-machine configuration, follow the instructions in Running the Windows Communication Foundation Samples.

Important note Important

The samples may already be installed on your computer. Check for the following (default) directory before continuing.

<InstallDrive>:\WF_WCF_Samples

If this directory does not exist, go to Windows Communication Foundation (WCF) and Windows Workflow Foundation (WF) Samples for .NET Framework 4 to download all Windows Communication Foundation (WCF) and WF samples. This sample is located in the following directory.

<InstallDrive>:\WF_WCF_Samples\WCF\Extensibility\Syndication\JsonFeeds

Show:
© 2014 Microsoft