Silverlight: Using Returned JSON

Overview

Using JSON formatted data instead of XML can be an advantage when optimum download speed is desired and the data doesn't require the use of XML attributes. While GZip compression often minimizes the size differences between XML and JSON, it may not be sufficient due to the overhead caused by the XML schema in use. In other cases you may need to interact with JavaScript and interoperability will be easier using JSON.

The example below use JSON formatted data fetched from http://api.flickr.com/services/feeds/photos_public.gne?format=json&nojsoncallback=1.

Using the DataContractJsonSerializer Class

Similar to the XmlSerializer class, DataContractJsonSerializer maps data from a JSON file into strongly managed objects.

Example

The following classes are used to store the received data in strongly-typed objects. Note the use of the Name property on the DataMember attribute to rename the data into the correct naming convention used in .NET.

C# Example
Visual Basic Example

The following example shows how to take an existing stream and deserialize the JSON data into strongly-typed classes and output the source URL for each photo.

C# Example
Visual Basic Example

Using the JsonObject Class

You can also work with JSON data in a weakly typed manner using the JsonObject, JsonArray, and JsonPrimitive classes. These classes can be used in conjunction with LINQ to iterate over the data. Importing the System.Json.dll will increase your XAP approximately 21kB.

Example

The following example shows how to take an existing stream, and using the weakly typed JSON classes, sort the results and output some details.

C# Example
Visual Basic Example

Further Reading

Related information on the web is listed below.