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…
2 |     "some_number": 108.541, | 
 
3 |     "date_time": "2011-04-13T15:34:09Z", | 
 
4 |     "serial_number": "SN1234" | 
 
 
 
into..
1 | using System.Web.Script.Serialization; | 
 
3 | var jss = new JavaScriptSerializer(); | 
 
4 | var dict = jss.Deserialize<dynamic>(jsonText); | 
 
6 | Console.WriteLine(dict["some_number"]);  | 
 
7 | Console.WriteLine(dict["more_data"]["field2"]);  | 
 
 
 
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:
3 | var jsonText = File.ReadAllText("mydata.json"); | 
 
5 | var jsp = new JsonParser(){CamelizeProperties = true}; | 
 
6 | dynamic json = jsp.Parse(jsonText); | 
 
8 | Console.WriteLine(json.SomeNumber);  | 
 
9 | Console.WriteLine(json.MoreData.Field2);  | 
 
 
 
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.
Are you a 
Git user? Let me help you make project management with Git simple. Checkout 
Gitpilot.
 
-JP
 
 
No comments:
Post a Comment