Deserialize JSON to a dynamic object

In C# you can use the System.Web.Helpers.Json Class to deserialize JSON into a dynamic object. This will save you a boat load of time if you are loading from a remote API.

For example, attempting to read from the Yahoo API for currency rates returns JSON in the format:

{
   "query":{
      "count":5,
      "created":"2013-08-16T19:03:38Z",
      "lang":"en-US",
      "results":{
         "rate":[
            {
               "id":"USDUSD",
               "Name":"USDUSD=X",
               "Rate":"0.00",
               "Date":"N/A",
               "Time":"N/A",
               "Ask":"N/A",
               "Bid":"N/A"
            },
            {
               "id":"EURUSD",
               "Name":"EUR to USD",
               "Rate":"1.3336",
               "Date":"8/16/2013",
               "Time":"3:03pm",
               "Ask":"1.3337",
               "Bid":"1.3335"
            },
            {
               "id":"AUDUSD",
               "Name":"AUD to USD",
               "Rate":"0.9202",
               "Date":"8/16/2013",
               "Time":"3:03pm",
               "Ask":"0.9205",
               "Bid":"0.9199"
            },
            {
               "id":"CADUSD",
               "Name":"CAD to USD",
               "Rate":"0.9687",
               "Date":"8/16/2013",
               "Time":"3:03pm",
               "Ask":"0.9688",
               "Bid":"0.9686"
            },
            {
               "id":"GBPUSD",
               "Name":"GBP to USD",
               "Rate":"1.5642",
               "Date":"8/16/2013",
               "Time":"3:03pm",
               "Ask":"1.5644",
               "Bid":"1.564"
            }
         ]
      }
   }
}

Writing a parser for this is... less than fun... especially when all we want are the rates. In the following example, the JSON is loaded and converted into a dictionary of currency/value pairs.

void LoadFeed()  
{
    // LOADS FROM: http://developer.yahoo.com/yql/console/?q=show%20tables&env=store://datatables.org/alltableswithkeys#h=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20%28%22USDUSD%22%2C%20%22EURUSD%22%2C%20%22AUDUSD%22%2C%20%22CADUSD%22%2C%20%22GBPUSD%22%29
    var url = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22EURUSD%22%2C%20%22AUDUSD%22%2C%20%22CADUSD%22%2C%20%22GBPUSD%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=";
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    using (StreamReader sr = new StreamReader(response.GetResponseStream()))
    {
        var json = sr.ReadToEnd();
        feedResults = Json.Decode(json);
        feedLoaded = true;
    }
}

public Dictionary<string, decimal> GetRates()  
{
    if (!feedLoaded)
        LoadFeed();

    var results = new Dictionary();
    foreach (dynamic rate in feedResults.query.results.rate)
    {
        results.Add(rate.id, decimal.Parse(rate.rate);
    }
    return results;
}

Note: This class is part of an assembly that is included in the ASP.NET MVC installation. You can include this assembly in build outputs by changing the "Copy Local" to true in the Reference Properties.

comments powered by Disqus