Starting from a new Silverlight Application, add references to the System.Runtime.Serialization and System.ServiceModel.Web assemblies.
At the top of the Page.xaml.cs code page, add the highlighted using statements.
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.
Within the Button_Click method, let’s start by creating a new instance of the Person class.
Using DataContractJsonSerializer the person object can be converted to a JSON string.
Let’s add a message box to display the JSON string.
Now let’s convert the JSON string (denoted by the “json” variable) back into a Person object (denoted by “person2”).
Lastly, just to confirm that de-serialized object is correct, display the property values of “person2”.
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.
The second popup displays properties from the de-serialized person.