Thursday, November 1, 2012

e Best JSON Parser for Silverlight and C#/.NET


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…
1{
2    "some_number": 108.541,
3    "date_time""2011-04-13T15:34:09Z",
4    "serial_number""SN1234"
5    "more_data": {
6        "field1": 1.0
7        "field2""hello"
8    }
9}
into..
1using System.Web.Script.Serialization;
2 
3var jss = new JavaScriptSerializer();
4var dict = jss.Deserialize<dynamic>(jsonText);
5 
6Console.WriteLine(dict["some_number"]); //outputs 108.541
7Console.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:
1using FridayThe13th;
2 
3var jsonText = File.ReadAllText("mydata.json");
4 
5var jsp = new JsonParser(){CamelizeProperties = true};
6dynamic json = jsp.Parse(jsonText);
7 
8Console.WriteLine(json.SomeNumber); //outputs 108.541
9Console.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