FridayThe13th the Best JSON Parser for Silverlight and C#/.NET
August 11, 2011 29 Comments
Up until a couple of months ago I was writing most of my code using WPF. Recently, a project came up where Silverlight made more sense to use. I’d thought that wouldn’t be a problem since I’d just use JavaScriptSerializer [wrote about it here] like I did for my WPF project.
Uh oh. It turns out that Silverlight doesn’t have JavaScriptSerializer. Never fear! DataContractJsonSerializer is here! Or so I thought.
It turns out that if you want to use DataContractJsonSerializer you must actually create POCOs to backup this “data contract.” I didn’t want to do that.
I wanted to turn this…
{ "some_number": 108.541, "date_time": "2011-04-13T15:34:09Z", "serial_number": "SN1234" "more_data": { "field1": 1.0 "field2": "hello" } }
into..
using System.Web.Script.Serialization; var jss = new JavaScriptSerializer(); var dict = jss.Deserialize<dynamic>(jsonText); Console.WriteLine(dict["some_number"]); //outputs 108.541 Console.WriteLine(dict["more_data"]["field2"]); //outputs hello
So I set out to write my own JSON parser. I call it FridayThe13th… how fitting huh? Now, using either Silverlight or .NET 4.0, you can parse the previous JSON into the following:
using FridayThe13th; var jsonText = File.ReadAllText("mydata.json"); var jsp = new JsonParser(){CamelizeProperties = true}; dynamic json = jsp.Parse(jsonText); Console.WriteLine(json.SomeNumber); //outputs 108.541 Console.WriteLine(json.MoreData.Field2); //outputs hello
Since I work with a lot of Ruby on Rails backends, I want to add a property “CamelizeProperties” to turn “some_number” into “SomeNumber”… it’s more .NET like.
Try it! You can find it on Github. Oh yeah… it’s also faster than that other .NET JSON library that everyone uses.
Are you a Git user? Let me help you make project management with Git simple. Checkout Gitpilot.
If you made it this far, read my blog on software entrepreneurship and follow me on Twitter: @jprichardson.
-JP