Believe it or not, JavaScript is everywhere. All new websites are using it. And since people can see it everywhere, all customers are asking for it as well. JavaScript got a very nice data structure for passing data back and forth by using JSON (JavaScript Object Notation). Generating JSON objects in .Net is just so easy, either you can use built-in JavaScriptSerializer or if you are using Web Service, just enable the ScriptServices and your objects will be converted to JSON automatically (based on Context). But parsing JSON on server side could be tricky.
Since I needed this JSON Parser badly in my project, I started to searched and found a very clean solution for it (thanks to Shawn Weisfeld for sharing it). The idea is, we can use Dynamic data type in order to deal with JSON strings, so you can use almost the same code that you have used in your JavaScript source, on the server side. The drawback is, you will lose intelliSense, and of course you have to use .Net 4.0. So if you are planing to use it in older versions, then you came to the wrong place.
Using JSON Parser
You can simply view the source code on github or download it.
Using it is so simple. I have added an extension to string class that will do the trick. If you are not familiar with Extension Methods, I have an article for you.
string jsonStr; // it can be like { a:{b:1}, c:[] } dynamic parsedStr = jsonStr.ParseJSON(); // you need to add "Using Cheraq.Extensions;" // to access b, you can use int b = (int)parsedStr.a.b; // this can lead to error if a is null int? safeB = parsedStr.a != null? (int?)parsedStr.a.b : (int?)null;
Hope you will find it useful.
