Richard Howells' Blog

Using C# dynamic to help parsing JSON

Start here with lots of good stuff from Tomas http://www.tomasvera.com/programming/using-javascriptserializer-to-parse-json-objects/

As mentioned, the JSON serializer returns Dictionary<string, object>.  This is inconvenient in a strongly typed environment like C#.   The entries in the dictionary vary through being both ArrayLists and further Dictionaries.  In C# we’d normally need to keep casting them to the correct type before we access properties and methods.

Enter dynamic!  In C#, dynamic allows you to simply assume that methods and properties will be there at run time.  That truth is checked at run time so you may see exceptions if you are wrong.  It did allow me to retrieve a JSON result from Google's Geocoding service and extract data from it like so…

                var geoData = jsSerializer.Deserialize<Dictionary<string, dynamic>>(rv);

                if (geoData["status"] == "OK")

                    latitude = Convert.ToSingle(geoData["results"][0]["geometry"]["location"]["lat"]);

Not the prettiest code in the world, but short.

As Tomas points out in his article, you can get to the same answer, more strongly typed, by creating a series of classes to map the JSON.  But when you want a quick and short answer, this will do.

 

Posting Archive
Copyright 2002-15 by Dynamisys Ltd