JSON Deserialization Made Simple With System.Web.Helpers and List<dynamic>

Posted on Feb 03, 2011

Been playing with WebMatrix and have come across some crazy and beautiful code that I really liked in the FourSquare helper on CodePlex. Check this method out, which returns a graph of friends from the fourquare api

Notice how tight this code is. And note the crazy dynamic typing that C#4 provides in combination with the Json.Decode method. If you are wondering where that JSON.Decode method came from, it is from System.Web.Helpers -- you can use this dll anywhere, doesn't have to be with WebMatrix or Razor. Here's a link to the docs on System.Web.Helpers.Json: http://msdn.microsoft.com/en-us/library/system.web.helpers.json(VS.99).aspx

Serialization and JSON have long been painful in .NET because of .NET's strong typing. This got better with the C# dynamic keyword (see this post and this post) but nothing is as elegant as the code above.

Notice how the two dynamic lists get created which are then manipulated with a LINQ lambda query. Nice! Having dealt so often with either manually mapping JSON to CLR objects and/or dealing with arrays nested in arrays nested in arrays, I'm absolutely loving this.