Click here to Skip to main content
12,244,489 members (49,428 online)
Click here to Skip to main content
Add your own
alternative version

Stats

272.2K views
105 bookmarked
Posted

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

, 12 Feb 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
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:  

{
  "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:  

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 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;
    // 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 WebClient() 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

License

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

Share

About the Author

Mikhail-T
Web Developer
United States United States
Coding is awesome!

You may also be interested in...

Comments and Discussions

 
PraiseMade Easy? Pin
globalgb15-Nov-15 7:48
memberglobalgb15-Nov-15 7:48 
GeneralMy vote of 5 Pin
GrumpyPants17-Sep-15 9:48
memberGrumpyPants17-Sep-15 9:48 
QuestionJSON Pin
Priyanka Thota23-Jun-15 6:59
memberPriyanka Thota23-Jun-15 6:59 
QuestionHow to handle JSON that has multiple data sets? Pin
Danny MacDonald8-Feb-15 15:02
memberDanny MacDonald8-Feb-15 15:02 
AnswerRe: How to handle JSON that has multiple data sets? Pin
Danny MacDonald8-Feb-15 15:10
memberDanny MacDonald8-Feb-15 15:10 
QuestionMultiple records Pin
Mohsin Mustufa2-Nov-14 7:08
memberMohsin Mustufa2-Nov-14 7:08 
GeneralMy vote of 1 Pin
Dmitry Kirsanov19-Jun-14 6:09
memberDmitry Kirsanov19-Jun-14 6:09 
GeneralMy vote of 5 Pin
Chris8752-Sep-14 3:25
professionalChris8752-Sep-14 3:25 
QuestionHow to access T and iterate Pin
suid00129-May-14 12:57
membersuid00129-May-14 12:57 
AnswerRe: How to access T and iterate Pin
Mikhail-T30-May-14 10:08
memberMikhail-T30-May-14 10:08 
GeneralRe: How to access T and iterate Pin
suid00130-May-14 17:42
membersuid00130-May-14 17:42 
QuestionI got a JsonReaderException Pin
nicocia10-Feb-14 5:06
membernicocia10-Feb-14 5:06 
AnswerRe: I got a JsonReaderException Pin
Mikhail-T10-Feb-14 5:28
memberMikhail-T10-Feb-14 5:28 
GeneralRe: I got a JsonReaderException Pin
nicocia10-Feb-14 5:38
membernicocia10-Feb-14 5:38 
Hi Mikhail and thanks for your quick answer. I followed your post step by step (I am new..)

this is the value of json_data:

<!DOCTYPE html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7 lang="en""> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8" lang="en"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9" lang="en"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en"> <!--<![endif]-->
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
 
    <title>Open Exchange Rates</title>
    <meta name="description" content="Free, hourly-updated exchange rates - a simple, accurate, open-source JSON API. Free for personal use, a bargain for everybody else.">
 
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:400,700">
    <link rel="stylesheet" type="text/css" href="/css/main.min.0006.css" />
 
    <link href="/favicon.ico" type="image/x-icon" rel="shortcut icon" />
    <link rel="canonical" href="https://openexchangerates.org/"/>
    <!--[if lt IE 9]>
        <script src="/js/html5.js"></script>
    <![endif]-->
 
    <script>var _gaq = _gaq || [];_gaq.push(['_setAccount', 'UA-31023525-1']);_gaq.push(['_setDomainName', 'openexchangerates.org']);_gaq.push(['_setAllowLinker', true]);_gaq.push(['_trackPageview']);(function() {var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);})();</script>
</head>
 
<body class="hfeed home">
 
    <header class="site-header cf" role="banner">
        <div class="container">
            <div class="site-logo">
                <a href="/" title="Exchange Rates API, JSON format, for Developers"><span class="star">$</span> &nbsp;open exchange rates</a>
            </div>
 

            <ul class="site-nav inline-block-list">
<!--
                <li>
                    <a href="/api-examples">API Examples</a>
                </li>
-->
 
                <li>
                    <a href="/about">About</a>
                </li>
 
                <li>
                    <a href="/showcase">Showcase</a>
                </li>
 
                <li>
                    <a href="/documentation">Documentation</a>
                </li>
 
                <li>
                    <a class="get-started" href="/signup">Get Your App ID</a>
                </li>
            </ul>
        </div>
    </header>
 

        <div class="site-promo">
            <div class="container">
                <h1>
                    Real-time exchange rates &amp;<br/>
                    currency conversion JSON API
                </h1>
                <p class="description">
                    Simple, reliable rates for developers &ndash; with 165 currencies and more.
                </p>
 
                <div class="cta-option">
                    <a class="btn-download" href="/signup" title="Get Your Open Exchange Rates App ID here">
                        <strong>Get Instant Access</strong>
                    </a>
                </div>
 
                <div class="example">
 
<pre class="latest-json prettyprint inactive"><div class="toggle">{ <a href="#" title="Click to view an example API response">&rarr; click to test API response</a> }</div><div class="result" style="display:none">/* latest.json (32 mins ago) */
{
  "timestamp": 1392044462,
  "base": "USD",
  "rates": {
    "AED": 3.67323,
    "AFN": 56.517325,
    "ALL": 102.958999,
    "AMD": 414.031002,
    /* <a target="_blank" href="/currencies" title="Click to view the list of currencies supported by Open Exchange Rates">165 currencies</a> */
    "YER": 214.919,
    "ZAR": 11.1218,
    "ZMK": 5253.075255,
    "ZMW": 5.602652,
    "ZWL": 322.355006
  }
}<div style="display:none;" class="pull-right"><a href="" title=""><small>more examples &rarr;</small></a></div></div></pre>
                </div>
 
            </div>
        </div>
 

 

        <aside class="trusty aside">
            <div class="container">
 
                <div class="trusted-by">Trusted by thousands &ndash; including:</div>
 
                <ul class="inline-block-list">
                    <li><img src="/img/logos/shopify.gif" title="Shopify - the powerful ecommerce website solution, providing everything you need to create an online store" alt="Shopify"></li>
 
                    <li><img style="height: 42px; margin:-6px -11px -4px -14px" src="/img/logos/etsy.png" title="Etsy - Your place to buy and sell all things handmade, vintage, and supplies" alt="Etsy"></li>
 
                    <li><img src="/img/logos/fab.gif" title="Fab.com - discover everyday design products at great prices, connect with the world's most exciting designers, and share your favorite design inspirations." alt="Fab.com"></li>
 
                    <li><img style="margin: 0 -6px 0 -7px;" src="/img/logos/justgiving.gif" title="JustGiving - Online fundraising donations and ideas" alt="JustGiving"></li>
 
                    <li><img style="margin: -7px -2px 0 -3px" src="/img/logos/braintree.gif" title="Braintree Payments - Accept payments in your app or website" alt="Braintree"></li>
 
                    <li><img style="margin: 2px 0px 0 -4px; height: 28px" src="/img/logos/wego.gif" title="Wego Flight Search - Save time, pay less, travel more" alt="Wego"></li>
 
                    <li><img style="margin: 0px -7px 0 -5px; height: 19px" src="/img/logos/coinbase.gif" title="Coinbase - Your Hosted Bitcoin Wallet" alt="Coinbase"></li>
 
                    <li><img style="height: 18px; margin: 0 -2px 0 0;" src="/img/logos/flattr.gif" title="Flattr Social Micropayments - Big change through small donations" alt="Flattr"></li>
 
                    <li><img style="margin:-6px 0 0 -3px" src="/img/logos/woocommerce.gif" title="WooCommerce by WooThemes - An e-commerce toolkit that helps you sell anything." alt="WooCommerce"></li>
 
<!--                    <li><img style="height: 28px; margin: 1px -5px 0 -3px" src="/img/logos/gumroad.gif" title="Gumroad - Share and sell anything, directly to your followers" alt="Gumroad"></li> -->
                </ul>
            </div>
        </aside>
 
    <div class="site-content">
        <div class="container">
 

 
        <div class="alert alert-block alert-danger" style="text-align:center;">
            <h4>Notice: App ID Required</h4>
            As per public notices beginning June 2012, an App ID is required to access the Open Exchange Rates API.<br/>
            It's free for personal use, a bargain for your business. You can <a href="/signup" title="Get Your Open Exchange Rates App ID here"><strong>sign up here &raquo;</strong></a>
        </div>
        <hr/>
 

 
    <br>
    <p class="clearfix alert alert-success" style="text-align:left">
        <strong>Monday 10th February: </strong>
        Looking for an alternative to the shut-down iGoogle calculator/exchange rate service? Open Exchange Rates features up-to-date and historical rates for 165 world currencies, in a simple and reliable JSON API. Get started in minutes! </p>
 

            <div class="lead">
                <h2>Simple, Fast &amp; Accurate Exchange Rates API</h2>
 
                <div class="grid">
                    <div class="grid-cell">
                        <h3><span class="star">&#9733; </span>&nbsp;Real-time &amp; Historical Rates</h3>
                        <p>For maximum consistency and unbiased data, <strong>exchange rates for 165 world currencies</strong> are tracked from multiple sources and blended algorithmically, with historical data back to 1999.</p>
                    </div>
 
                    <div class="grid-cell">
                        <h3><span class="star">&#9733; </span>&nbsp;Suitable For All Applications</h3>
                        <p>The <strong>exchange rates API</strong> is delivered in simple and portable JSON format with <strong>HTTPS</strong> and <strong>JSONP</strong> support, for fast and easy use in any language. Check out the <a href="/showcase" title="Showcase of Open Exchange Rates Apps">showcase</a> for examples!</p>
                    </div>
                </div>
 
                <br/>
                <h2>Why use Open Exchange Rates?</h2>
                <p class="in-the-wild">Live and historical exchange rates for 165 currencies in a simple JSON API.</p>
                <p class="in-the-wild">Unbiased consistency, fantastic email support and documentation.</p>
                <p class="in-the-wild">Free for personal use, a bargain for your business.</p>
 
                <div class="cta-option">
                    <a class="btn-download" href="/signup" title="Get Your Open Exchange Rates App ID here">
                        <strong>Get Started Here</strong>
                    </a>
                </div>
            </div>
 
        </div>
    </div>
 

    <footer class="site-footer" role="contentinfo">
        <div class="container">
            <p>
                <a href="http://twitter.com/share" class="twitter-share-button" data-count="inline" data-via="josscrowcroft" data-url="http://openexchangerates.org/" data-text="Open Exchange Rates API: realtime currency conversion data for developers">Tweet</a>
                &nbsp; &nbsp;
                <g:plusone size="medium" annotation="none"></g:plusone>
                &nbsp; &nbsp;
                <a class="FlattrButton" style="display:none;" rev="flattr;button:compact;" href="http://openexchangerates.org"></a><noscript><a href="http://flattr.com/thing/622410/Open-Exchange-Rates-API" target="_blank"><img src="https://api.flattr.com/button/flattr-badge-large.png" alt="Flattr this" title="Flattr this" border="0" /></a></noscript>
            </p>
 
<!--            <p>Just deployed a few upgrades &ndash; please <a href="mailto:support@openexchangerates.org" title="Contact Us" rel="nofollow" target="_blank">get in touch</a> if anything's up.</p> -->

            <p>Any questions? Please <a href="mailto:support@openexchangerates.org" title="Contact Us" rel="nofollow" target="_blank">get in touch</a>!</p>
 
<!--            <p>A project by <a href="http://twitter.com/josscrowcroft">Joss</a> and friends. Hosting provided by the excellent <a href="http://my.tsohost.com/aff.php?aff=1448" title="Best UK WordPress and Shared Hosting" target="_blank">TSOHost</a>.<p> -->
 
            <p style="color:#777">
                <a href="/signup" title="Open Exchange Rates - App ID Signup">Sign up</a>
                &nbsp;|&nbsp; <a href="/login" title="Open Exchange Rates Account Login">Log in</a>
                &nbsp;|&nbsp; <a href="/faq" title="Open Exchange Rates FAQ">FAQ</a>
                &nbsp;|&nbsp; <a href="/contact" title="Contact Open Exchange Rates">Contact</a>
                &nbsp;|&nbsp; <a href="/sitemap" title="Open Exchange Rates Sitemap">Sitemap</a>
                <br/>
            </p>
 
            <p><a href="http://my.tsohost.com/aff.php?aff=1448" title="Best UK WordPress and Shared Hosting" target="_blank"><img src="/img/tsohost-brand.gif" alt="TSOHost - UK Hosting Provider" /></a></p>
 
            <p class="small">
                Code and content &copy; 2011&ndash;2014 <a href="/" title="Reliable Exchange Rate API, JSONP and HTTPS support">openexchangerates.org</a>.
                All usage of Open Exchange Rates website, API and services are subject to the <a href="/terms" title="Terms &amp; Conditions">Terms &amp; Conditions</a> and <a href="/privacy" title="Privacy Policy">Privacy Policy</a>.
            </p>
 

thanks again,
nico
        </div>
    </footer>
 
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
    <script src="/js/libs/prettify/prettify.js"></script>
    <script src="/js/mailcheck.min.js"></script>
    <script src="/js/libs/accounting.min.js"></script>
    <script src="/js/libs/money.min.js"></script>
    <script type="text/javascript">fx.base="USD";fx.rates={};$('[data-v]').each(function(){fx.rates[$(this).text().toUpperCase().trim()]=$(this).data('v')})</script>
    <script src="/js/main.js"></script>
    <script src="/js/bootstrap-popover-tooltip.min.js"></script>
    <script type="text/javascript">
        $('.more').popover({
            placement: 'top',
            trigger: 'hover'
        }).mouseout(function () {
            $(this).popover('destroy').popover({
                placement: 'top',
                trigger: 'hover'
            });
        });
    </script>
 
</body>
</html>

AnswerRe: I got a JsonReaderException Pin
Mikhail-T10-Feb-14 13:06
memberMikhail-T10-Feb-14 13:06 
GeneralRe: I got a JsonReaderException Pin
nicocia10-Feb-14 22:23
membernicocia10-Feb-14 22:23 
QuestionMessage Removed Pin
AndrewGray123418-Jul-13 0:05
memberAndrewGray123418-Jul-13 0:05 
AnswerRe: THIS DOES NOT WORK Pin
Mikhail Tsennykh18-Jul-13 8:02
memberMikhail Tsennykh18-Jul-13 8:02 
QuestionRe: Use C# to get JSON Data from the Web and Map it to .NET Class => Made Easy! Pin
Omage femi17-May-13 7:46
memberOmage femi17-May-13 7:46 
QuestionTwo minor questions Pin
BillWoodruff30-Apr-13 2:26
memberBillWoodruff30-Apr-13 2:26 
AnswerRe: Two minor questions Pin
Mikhail Tsennykh30-Apr-13 5:43
memberMikhail Tsennykh30-Apr-13 5:43 
Suggestion'Paste JSON As Classes' in Visual Studio Pin
Dave Kerr29-Apr-13 6:24
mvpDave Kerr29-Apr-13 6:24 
GeneralRe: 'Paste JSON As Classes' in Visual Studio Pin
BillWoodruff30-Apr-13 2:23
memberBillWoodruff30-Apr-13 2:23 
GeneralRe: 'Paste JSON As Classes' in Visual Studio Pin
Dave Kerr30-Apr-13 3:17
mvpDave Kerr30-Apr-13 3:17 
GeneralRe: 'Paste JSON As Classes' in Visual Studio Pin
Mikhail Tsennykh30-Apr-13 5:30
memberMikhail Tsennykh30-Apr-13 5:30 
GeneralRe: 'Paste JSON As Classes' in Visual Studio Pin
Dave Kerr30-Apr-13 5:37
mvpDave Kerr30-Apr-13 5:37 
QuestionExample for POST JSON Pin
developer24724-Jan-13 14:49
memberdeveloper24724-Jan-13 14:49 
QuestionMultilayered JSON results Pin
John Mike H.19-Nov-12 10:03
memberJohn Mike H.19-Nov-12 10:03 
AnswerRe: Multilayered JSON results Pin
Mikhail Tsennykh19-Nov-12 12:27
memberMikhail Tsennykh19-Nov-12 12:27 
GeneralRe: Multilayered JSON results Pin
John Mike H.20-Nov-12 4:58
memberJohn Mike H.20-Nov-12 4:58 
QuestionMixed JSon to Object Pin
rhythmdivine7-Oct-12 4:27
memberrhythmdivine7-Oct-12 4:27 
AnswerRe: Mixed JSon to Object Pin
Mikhail Tsennykh7-Oct-12 8:05
memberMikhail Tsennykh7-Oct-12 8:05 
GeneralRe: Mixed JSon to Object Pin
rhythmdivine7-Oct-12 11:12
memberrhythmdivine7-Oct-12 11:12 
GeneralRe: Mixed JSon to Object Pin
Mikhail Tsennykh9-Oct-12 12:14
memberMikhail Tsennykh9-Oct-12 12:14 
GeneralRe: Mixed JSon to Object Pin
rhythmdivine24-Apr-14 6:21
memberrhythmdivine24-Apr-14 6:21 
GeneralMy vote of 5 Pin
manoj kumar choubey18-Jul-12 21:49
membermanoj kumar choubey18-Jul-12 21:49 
QuestionWhy ? DataContractJsonSerializer works fine. Pin
Nicolas Dorier6-Jun-12 5:01
memberNicolas Dorier6-Jun-12 5:01 
AnswerRe: Why ? DataContractJsonSerializer works fine. Pin
Mikhail Tsennykh6-Jun-12 7:37
memberMikhail Tsennykh6-Jun-12 7:37 
GeneralRe: Why ? DataContractJsonSerializer works fine. Pin
Nicolas Dorier6-Jun-12 8:14
memberNicolas Dorier6-Jun-12 8:14 
GeneralMy vote of 5 Pin
Othello744-Jun-12 22:40
memberOthello744-Jun-12 22:40 
GeneralRe: My vote of 5 Pin
Mikhail Tsennykh5-Jun-12 7:17
memberMikhail Tsennykh5-Jun-12 7:17 
GeneralMy vote of 5 Pin
parvus4-Jun-12 12:30
memberparvus4-Jun-12 12:30 
GeneralRe: My vote of 5 Pin
Mikhail Tsennykh4-Jun-12 12:47
memberMikhail Tsennykh4-Jun-12 12:47 

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.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160426.1 | Last Updated 12 Feb 2014
Article Copyright 2012 by Mikhail-T
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid