Formattatore di feed (JSON)

Nell’esempio JsonFeeds viene illustrato come serializzare un'istanza di una classe SyndicationFeed in JSON (JavaScript Object Notation) usando un SyndicationFeedFormatter personalizzato e DataContractJsonSerializer.

Architettura dell'esempio

Nell'esempio viene implementata una classe denominata JsonFeedFormatter che eredita da SyndicationFeedFormatter. La classe JsonFeedFormatter si basa sul DataContractJsonSerializer per leggere e scrivere e i dati in formato JSON. Internamente, il formattatore usa un set personalizzato di tipi di contratto dati denominati JsonSyndicationFeed e JsonSyndicationItem per controllare il formato dei dati JSON prodotti dal serializzatore. Questi dettagli di implementazione sono nascosti dall'utente finale, consentendo l'esecuzione di chiamate rispetto alle classi SyndicationFeed e SyndicationItem standard.

Scrittura di feed JSON

La scrittura di un feed JSON può essere ottenuta usando il JsonFeedFormatter (implementato in questo esempio) con DataContractJsonSerializer come illustrato nel codice di esempio seguente.

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

Lettura di un feed JSON

L'ottenimento di un SyndicationFeed da un flusso di dati formattati JSON può essere eseguito tramite JsonFeedFormatter come illustrato nel codice seguente.

//Read in the feed using the DataContractJsonSerializer

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

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

SyndicationFeed feedRead = formatter.Feed;

Per impostare, compilare ed eseguire l'esempio

  1. Assicurarsi di aver eseguito la Procedura di installazione singola per gli esempi di Windows Communication Foundation.

  2. Per compilare l'edizione in C# o Visual Basic .NET della soluzione, seguire le istruzioni in Building the Windows Communication Foundation Samples.

  3. Per eseguire l'esempio in un solo computer o tra computer diversi, seguire le istruzioni in Esecuzione degli esempi di Windows Communication Foundation.