JSON.net and XML to JSON from the Cloud for WP7 (Windows Phone 7)

I have been writing more and more apps that need to pull data from the Cloud. These apps are at the mercy of the API that is provided by the cloud service. JSON.net is an invaluable tool that has helped alleviate a lot of the annoyance associated with pulling data over HTTP. In this post, I aim to show you the routes I took to standardize some annoying XML for use in a Windows Phone 7 application.


PHP XML->JSON for WP7

PHP XML->JSON for WP7

This application needs to pull an XML formatted menu that is published weekly for a college campus cafeteria. The XML format is not one that I would have personally used. To make it an appropriate format, I decided to write a PHP script to deserialize the XML and re-serialize it into JSON. One immediate advantage of parsing the XML and reformatting it is that a change to the third party format, although breaking the app temporarily, would allow me to make a fix on the script level rather than having to recompile and redeploy the WP7 app to all my current users. This parsing only required a few lines of code using PHP5′s built in serialization tools.

JSON Output for WP7

JSON Output for WP7

With my data now in the format that I want, I can focus attention on the Windows Phone 7 (WP7) client.

 

 

JsonNet C# WP7 nuget

JsonNet C# WP7 nuget

I pulled down the latest JSON.net package using nuget in Visual Studio.

 

 

Web Request wp7 JSON

Web Request wp7 JSON

Then I created a class to handle all data transactions. I called this the DataGrabber. It essentially makes calls asynchronously and stores the result in a collection that can be retrieved by the consumer(s) of this class. When the request finishes, the result is parsed into a C# object created using JSON.net and an online JSON->C# object creation tool. This tool is incredibly handy and can be found at http://json2csharp.com/. A callback is fired once the deserialization is complete and allows the consumer to retrieve the data using a unique request identifier provided in said callback.



The consumer can then set the ViewModel property by farming the data required out of the request’s return value. With a bit more work and some UI polish a Pubcenter ad can be inserted and the app is ready to be posted to the WP7 Apphub!

Leave a Reply

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