Saturday, November 20, 2010

Parsing Json using C# dynamic

I had an application where I had to get data from  a web service. Get some name data from that service and then get relevant images from another web service. I was wondering how to do that because my application is MVC2 with Javascript and JQuery.
My first approach was to try to get the results  from first web service in the view page,  manipulate the result with JQuery, extract the information and then make the second web service call. However, I thought it was clumsy.
Then I came across JavascriptSerializer. But it required that I declare a complete class for the Javascript object which I was reluctant to do. Then I looked at Json.NET. Elegant solution but I thought was an overkill for what I wanted to do.
Then I came across C# 4.0, Dynamic Programming and JSON  by Nikhil which is also great, but again for my application was an overkill.
Finally I hit pay dirt when I saw this great article  Using C# 4.0 and dynamic to parse JSON by Shawn which is wonderful. Excellent piece of code to extract what I wanted. Almost like working with Javascript in C#. I had to do the minor  bug correction by Drew mentioned in serialize JSON into C# dynamic object?.
I used the code and I was able to scan through the objects like I would do in Javascript notation.
Excellent tool to have in your arsenal when you want to work with web services which returen JSON in MVC.

No comments:

Post a Comment