Proper JSON Deserialization in Windows Phone 7

I’m working on a Windows Phone 7 project that requires me to read some JSON data. The data is a fairly innocuous list of key/object pairs in this form:
[code lang=”js”]

So my first port of call was the class that has been mentioned a number of times for using JSON over WCF: our friend the DataContractJsonSerializer. However, if you ask the DataContractJsonSerializer to deserialize the JSON above into a nice Dictionary<int, Person>, it fails.

After trying a few different jigs and japes, I eventually flipped the switch and tried serializing a Dictionary<int, Person> with the DataContractJsonSerializer. Here’s the steaming turd it came up with:
[code lang=”js”]

No wonder it couldn’t deserialize my sane JSON string. DataContractJsonSerializer is clearly insane. In mitigation, I think the insanity stems from the DataContract’s XML roots, where an element without a name would be crazy talk.

Luckily the sensible JSON.Net project has builds for Silverlight, which work fine in the April CTP of the Windows Phone 7 development tools. And you could always include the JSON.Net source code in your project if you want to make sure you can retain compatibility.

By referencing the Silverlight 3 build, I was able to deserialize my JSON into a Dictionary<int, Person> with a single line of code:
[code lang=”csharp”]
var myObjects = JsonConvert.DeserializeObject<Dictionary<int, Person>>(jsonString);

Lovely! Now I have green lights in my JSON tests using the Windows Phone 7 unit testing framework I mentioned earlier.

Join the Conversation


  1. Hello, I have a problem. Once you have the json code you can do the above, but how do I get it? Im supposed to get it from a .js file on the net, but I just cant mannage it. Any ideas?

Leave a comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: