Consume a JSON object in Silverlight

Here is how to consume a JSON object in Silverlight 2.

  1. Start with a JSON object:
    var Person = {
    "firstName": "John",
    "lastName": "Smith",
    "address": {
    "streetAddress": "21 2nd Street",
    "city": "New York",
    "state": "NY",
    "postalCode": 10021
  2. Create an entry point into Silverlight. You will need to add namespace System.Windows.Browser.
    JSON Html Bridge
  3. Next add C# classes to mirror the JSON object. It’s important to make sure the variables in the class are exactly how they appear in the JSON object, this is case sensitive.
    JSON C# classes
  4. Before adding the deserializing code, add references in your project for System.Runtime.Serialization, System.ServiceModel, and System.ServiceModel.Web.
    Add reference
  5. Now that the proper references are made in the project, we can finally write the code that deserializes the JSON object. The class that does all the magic is System.Runtime.Serialization.Json.DataContractJsonSerializer.
    Code for deserialzing a json object in silverlight
  6. Finally add some HTML and JavaScript to make this work. (To get the JSON object in a serialized form I am using the Prototype JavaScript library. That is where you’ll find the function Object.toJSON(). There are other ways to serialize a JSON object. Notably, if you are using the AJAX ASP.NET library, there is a function in there that does exactly the same thing as this call.)JavaScript
    function sendJSON(){ document.getElementById("SL").Content.Bridge.SendJSON(Object.toJSON(Person)); }
    <input type="button" value="send JSON to SL" onclick="sendJSON()" id="btnSendJSON" />

See this example in action.
Download the Source.


1 comment so far

  1. […] Consume a JSON Object in Silverlight (Corey Schuman) […]

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: