Use C# to get JSON Data from the Web and Map it to .NET Class => Made Easy! 转
2013-05-01 10:20
831 查看
http://www.codeproject.com/Tips/397574/Use-Csharp-to-get-JSON-Data-from-the-Web-and-Map-i
As an example, we will use http://openexchangerates.org site which provides latest currency rates formatted as JSONdata. Latest daily rates will be retrieved from this here.
It outputs currency data in the following JSON format:
Collapse | Copy Code
So, how do we retrieve them through C# on the server side and use them? Read on to find out.
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:
Collapse | Copy Code
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 to us by http://openexchangerates.org/latest.json:
Collapse | Copy Code
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
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'
Collapse | Copy Code
Here, at first, an instance of
Then, this
Deserialization is done via Json.NET library's method
In this example, a call to a universal method
Collapse | Copy Code
And that's it! Now you can do anything you need with the data you retrieved.
Good luck!
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.As an example, we will use http://openexchangerates.org site which provides latest currency rates formatted as JSONdata. Latest daily rates will be retrieved from this here.
It outputs currency data in the following JSON format:
Collapse | Copy Code
{ "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 libraryJson.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:
Collapse | Copy Code
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 to us by http://openexchangerates.org/latest.json:
Collapse | Copy Code
public class CurrencyRates{ public stringDisclaimer { get; set; } public stringLicense { get; set; } public int TimeStamp { get; set; } public stringBase { 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
Arrayor
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:
Collapse | Copy Code
using System.Net; using Newtonsoft.Json; // ... private static T _download_serialized_json_data<T>(stringurl) 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 stringwith 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.Netclass (a part of the .NET) downloads data from the specific URL (http://openexchangerates.org/latest.json in our case) as a plain
string.
Then, this
stringcontaining JSON data is mapped (deserialized) to any .NET class provided (
CurrencyRatesin 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:
Collapse | Copy Code
var url = "http://openexchangerates.org/latest.json"; var currencyRates = _download_serialized_json_data<CurrencyRates>(url);
And that's it! Now you can do anything you need with the data you retrieved.
Good luck!
History
6/4/12 - Initial publication相关文章推荐
- Get json formatted string from web by sending HttpWebRequest and then deserialize it to get needed data
- Use Jquery to get json data from the server-side php page
- Python Web-第六周-JSON and the REST Architecture(Using Python to Access Web Data)
- Use C# and the .NET Framework to develop your own plugin architecture
- .NET错误The 'targetFramework' attribute in the <compilation> element of the Web.config file is used only to target version 4.0 and later of the .NET Framework
- How To Use the ODBC .NET Managed Provider in Visual C# .NET and Connection Strings
- This function has none of Deterministic,no sql,or reads sql data in its declaration and binary logging is enabled(you *might* want to use the less safe log_bin_trust_function_creators variable
- How can selenium web driver get to know when the new window has opened and then resume its execution
- How To: Use DPAPI to Encrypt and Decrypt Data (C#/VB.NET)
- ruby get data and loop it from the template
- 【ActiveMQ】管理界面查看消息详情,报错/WEB-INF/tags/form/forEachMapEntry.tag PWC6199: Generated servlet error: The type java.util.Map$Entry cannot be resolved. It is indirectly referenced from required .class files
- [Android] Use Jsoup to grab the web data and process the data with string.indexOf()
- JsonToMap and getMapFromStrToMap
- Unable to get the project file from the Web Server(in .NET 2005 IDE)
- Unable to get the project ile from the web server错误的解决方法
- Unable to get the project ile from the web server的解决方法
- How to create a DLL library in C and then use it with C#
- Unable to find the requested .Net Framework Data Provider. It may not be installed
- WARNING: arch/arm/mach-omap2/built-in.o(.text+0x12cdc): Section mismatch in reference from the function mmc0_init() to the (unknown reference) .init.data:(unknown)
- To get the "month" from a DATE datatype