Click here to Skip to main content
15,885,244 members
Articles / Web Development
Tip/Trick

Use C# to get JSON Data from the Web and Map it to .NET Class => Made Easy!

Rate me:
Please Sign up or sign in to vote.
4.87/5 (39 votes)
12 Feb 2014CPOL2 min read 808.9K   120   49
Easy steps on how to get JSON formatted data from a web service, deserialize it, and map it to custom local class for further usage

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:  

JSON
{
  "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,
    // ... more values ...
  }
} 

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:  

C#
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:

C#
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;
    // attempt to download JSON data as a string
    try {
      json_data = w.DownloadString(url);
    }
    catch (Exception) {}
    // if string with JSON data is not empty, deserialize it to class and return its instance 
    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:  

C#
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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United States United States
Coding is awesome!

Comments and Discussions

 
AnswerRe: I got a JsonReaderException Pin
Mikhail-T10-Feb-14 12:06
Mikhail-T10-Feb-14 12:06 
GeneralRe: I got a JsonReaderException Pin
nicocia10-Feb-14 21:23
nicocia10-Feb-14 21:23 
QuestionMessage Closed Pin
17-Jul-13 23:05
AndrewGray123417-Jul-13 23:05 
AnswerRe: THIS DOES NOT WORK Pin
Mikhail-T18-Jul-13 7:02
Mikhail-T18-Jul-13 7:02 
QuestionRe: Use C# to get JSON Data from the Web and Map it to .NET Class => Made Easy! Pin
Omage femi17-May-13 6:46
Omage femi17-May-13 6:46 
QuestionTwo minor questions Pin
BillWoodruff30-Apr-13 1:26
professionalBillWoodruff30-Apr-13 1:26 
AnswerRe: Two minor questions Pin
Mikhail-T30-Apr-13 4:43
Mikhail-T30-Apr-13 4:43 
Suggestion'Paste JSON As Classes' in Visual Studio Pin
Dave Kerr29-Apr-13 5:24
mentorDave Kerr29-Apr-13 5:24 
GeneralRe: 'Paste JSON As Classes' in Visual Studio Pin
BillWoodruff30-Apr-13 1:23
professionalBillWoodruff30-Apr-13 1:23 
GeneralRe: 'Paste JSON As Classes' in Visual Studio Pin
Dave Kerr30-Apr-13 2:17
mentorDave Kerr30-Apr-13 2:17 
GeneralRe: 'Paste JSON As Classes' in Visual Studio Pin
Mikhail-T30-Apr-13 4:30
Mikhail-T30-Apr-13 4:30 
GeneralRe: 'Paste JSON As Classes' in Visual Studio Pin
Dave Kerr30-Apr-13 4:37
mentorDave Kerr30-Apr-13 4:37 
GeneralRe: 'Paste JSON As Classes' in Visual Studio Pin
BillWoodruff4-May-17 2:34
professionalBillWoodruff4-May-17 2:34 
QuestionExample for POST JSON Pin
developer24724-Jan-13 13:49
developer24724-Jan-13 13:49 
QuestionMultilayered JSON results Pin
John Mike H.19-Nov-12 9:03
John Mike H.19-Nov-12 9:03 
AnswerRe: Multilayered JSON results Pin
Mikhail-T19-Nov-12 11:27
Mikhail-T19-Nov-12 11:27 
GeneralRe: Multilayered JSON results Pin
John Mike H.20-Nov-12 3:58
John Mike H.20-Nov-12 3:58 
QuestionMixed JSon to Object Pin
Rupak Kr D7-Oct-12 3:27
Rupak Kr D7-Oct-12 3:27 
AnswerRe: Mixed JSon to Object Pin
Mikhail-T7-Oct-12 7:05
Mikhail-T7-Oct-12 7:05 
GeneralRe: Mixed JSon to Object Pin
Rupak Kr D7-Oct-12 10:12
Rupak Kr D7-Oct-12 10:12 
GeneralRe: Mixed JSon to Object Pin
Mikhail-T9-Oct-12 11:14
Mikhail-T9-Oct-12 11:14 
Great, that you got it at least partially working. Since I never worked with Silverlight, I might nto be able to help you with its specifics. We'll see.

As for not being able to map JSON to static class, this is not really a limitation. Static classes with static properties are designed to be used in a particular manner:
C#
var variable = StaticClass.StaticProperty();

Static classes cannot be inherited or have an interface, be a part of a list or collection, etc. Their main purpose is to be called directly or as an extensions of another classes.

On the other hand non-static classes can have interfaces and be inherited, and inherit from. They provide more flexibility that static ones.

Both types have their own place in C# (.NET) ecosystem where particular usage is enforced.

To work with data retrieved from JSON you shouldn't need to use static class (unless it is a specific requirment of Silverlight, which again I am not familiar with).

If you really need to use static class, you'll most probably have to map your dynamic class by manually:
C#
// Your user in a non-static class
var user = new User { /* user data */ };

// Map by hand to static class
YourStaticUsersClass.UserId = user.UserId;
YourStaticUsersClass.LoginId = user.LoginId;
YourStaticUsersClass.FirstName = user.FirstName;
// ... and similarly for all the properties ...

Once again you shouldn't be needing to explicitly use static class or properties, unless it is some requirement of Silverlight.

How is data retrieved from JSON should be used in your application? Can you give any sample code of how or where it is intended to be used?
GeneralRe: Mixed JSon to Object Pin
Rupak Kr D24-Apr-14 5:21
Rupak Kr D24-Apr-14 5:21 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey18-Jul-12 20:49
professionalManoj Kumar Choubey18-Jul-12 20:49 
QuestionWhy ? DataContractJsonSerializer works fine. Pin
Nicolas Dorier6-Jun-12 4:01
professionalNicolas Dorier6-Jun-12 4:01 
AnswerRe: Why ? DataContractJsonSerializer works fine. Pin
Mikhail-T6-Jun-12 6:37
Mikhail-T6-Jun-12 6:37 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.