Friday, May 15, 2009

Silverlight Serialization to JSON

This post will walkthrough the process of serializing and de-serializing an object to/from a JSON using Silverlight.

Starting from a new Silverlight Application, add references to the System.Runtime.Serialization and System.ServiceModel.Web assemblies.

 image

At the top of the Page.xaml.cs code page, add the highlighted using statements.

 image

Still in the Page.xaml.cs code page, add a definition of a Person class that we will ultimately serialize to JSON.  The class must be attributed with DataContract, a flag that denotes that the class (and all public members) are serializable.  In the screenshot below, I have explicitly added DataMember attributes to shorten the property names in the JSON string.

image

Add a Button to the XAML and add an event handler for the click event, so that the code in Page.xaml.cs looks like the following.

image 

Within the Button_Click method, let’s start by creating a new instance of the Person class.

image

Using DataContractJsonSerializer the person object can be converted to a JSON string.

image

Let’s add a message box to display the JSON string.

image

Now let’s convert the JSON string (denoted by the “json” variable) back into a Person object (denoted by “person2”).

image

Lastly, just to confirm that de-serialized object is correct, display the property values of “person2”.

image 

The final step is to run this code and see if it works!  Run the application in debug and click on the button you defined above to execute the serialization code.  The first popup displays the serialized Person as a JSON string.  The JSON is using the shorter member names defined using the DataMember attribute.

image

The second popup displays properties from the de-serialized person.

image 

No comments:

Post a Comment