Silverlight and JSON

Another artcile by Michael Schwarz, check it out here:

Silverlight 1.1 comes with an built-in JSON serializer which can serialize common data types like string, numbers and arrays. It includes a object serializer, too, I think it is nearly the same as in ASP.NET AJAX or Ajax.NET Professional.

I modified my IsolatedStorage demo and added a new method called GetFiles(string pattern) which will return an array of string containing the file names in the storage. Because I already did the managed JavaScript (DLR) demo in on of my earlier posts I’m now using C# (I love Silverlight, I can choose my favorite language all the time).

Because Silverlight (or the Scriptable methods) don’t support more complex data types until now (I hope this will change in future releases) we have to return a JSON string that will be parsed on the client-side JavaScript later.

The JavaScriptSerializer is included in the namespace System.Windows.Browser.Serialization. You have to create a new instance of the JavaScriptSerializer class and call the Serialize method which you pass the .NET object you want to serialize. In our example it is a string array we get as result of the IsolatedStorageFile.GetFiles method.

On the client-side JavaScript code I use the eval statement, hm, is not the best way to parse JSON, but the easiest. Of course you can use the ASP.NET AJAX parser or the JavaScript parser at

You can download this example here. For those of you don’t have Visual Studio Orcas installed I have included the binary files, too. So, simple double click on the TestPage.html. If you run the example you will see three message boxes: the first will display true if writing was sucessful, the second one will display the content of the file specified in the argument. The last message box will display all filenames in the storage.

read original

Leave a Reply

Your email address will not be published. Required fields are marked *