Introduction
This tip/trick demonstrates a complete and easy solution on how to get JSON formatted data from a web service, and map (deserialize) it to custom .NET class for further usage.
Sample Data
As an example, we will use https://openexchangerates.org service which provides latest currency rates formatted as JSON data. Here is a sample of how that data looks like:
{
"disclaimer": "This data is collected from various providers ...",
"license": "Data collected from various providers with public-facing APIs ...",
"timestamp": 1336741253,
"base": "USD",
"rates": {
"AED": 3.6731,
"AFN": 48.419998,
"ALL": 107.949997,
"AMD": 393.410004,
"ANG": 1.79,
"AOA": 94.949997,
}
}
So, how do we retrieve them through C# on the server side and use them? Read on to find out.
How To - Three Easy Steps
Step 1. Install Json.Net library
Json.NET library provides an easy, and de-facto, standard way to convert (serialize) .NET class to JSON data, and JSON data back to .NET class (deserialize).
The easiest way to install Json.Net library into your .NET project is via NuGet Package Manager Console by running this command:
install-package Newtonsoft.Json
Alternatively, if you need to install it manually, download it from its project page on CodePlex.
Step 2. Create .NET class which will match JSON data format
If you are using Visual Studio 2012+, you're in luck, since you can just paste a sample JSON data and it will create a class for you, To do that, first create a new class .cs file, select it in project explorer, than copy sample JSON data to clipboard, go to EDIT > Paste Special > Paste JSON as classes (thanks to Dave Kerr for this tip). More information on this feature here.
If that won't work for you, or you'd prefer to do it yourself, you'll need to define .NET class manually. It must exactly match the format of JSON data provided by openexchangerates.org:
public class CurrencyRates {
public string Disclaimer { get; set; }
public string License { get; set; }
public int TimeStamp { get; set; }
public string Base { get; set; }
public Dictionary<string, decimal> Rates { get; set; }
}
Note that property names are not case sensitive, but the name has to exactly match the JSON one. Also, notice how "rates" JSON property is matched to a Dictionary<string, decimal>
. If "rates" would have a singular value, they could alternatively be matched to an Array
or <code><code>IEnumerable
.
Step 3. Create a method to retrieve JSON data and map it to .NET class
Now we will create the following universal method that can be re-used for any .NET class, where 'T
' represents any .NET class that you need JSON data to be mapped to:
using System.Net;
using Newtonsoft.Json;
private static T _download_serialized_json_data<T>(string url) where T : new() {
using (var w = new WebClient()) {
var json_data = string.Empty;
try {
json_data = w.DownloadString(url);
}
catch (Exception) {}
return !string.IsNullOrEmpty(json_data) ? JsonConvert.DeserializeObject<T>(json_data) : new T();
}
}
Here, at first, an instance of <a href="http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx">WebClient()</a>
System.Net
class (a part of the .NET) downloads data from the specific URL as a plain string
.
Then, this string
containing JSON data is mapped (deserialized) to any .NET class provided (CurrencyRates
in our case).
Deserialization is done via Json.NET library's method JsonConvert.DeserializeObject<T>(json_data)
, which attempts to match all JSON fields to the same .NET class fields.
In this example, a call to a universal method _download_serialized_json_data<T>()
can look like this:
var url = "https://openexchangerates.org/api/latest.json?app_id=YOUR_APP_ID ";
var currencyRates = _download_serialized_json_data<CurrencyRates>(url);
(Please note: if you want to use data provided by openexchangerates.org, first you need to get your unique App Id here: https://openexchangerates.org/signup/free^, than replace YOUR_APP_ID
in the sample above.)
Final Note
And that's it! Now you can do anything you need with the data you've just retrieved.
Good luck!
History