Proper JSON Deserialization in Windows Phone 7

By | June 23, 2010

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"]
{
123:{"firstname":"Ben","lastname":"Gracewood"},
332:{"firstname":"Fred","lastname":"Fish"}
}
[/code]

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"]
{
"Key":123,"Value":{"firstname":"Ben","lastname":"Gracewood"},
"Key":332,"Value":{"firstname":"Fred","lastname":"Fish"}
}
[/code]

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);
[/code]

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

4 thoughts on “Proper JSON Deserialization in Windows Phone 7

  1. Ben Post author

    System.Json wasn’t available on Windows Phone 7 at the time of writing. Is it available now?

    Reply
  2. Fred

    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?

    Reply

Leave a Reply

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