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:
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:
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:
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.