Use C # To get JSON data from the web and map it to. Net class => made easy! Transfer

Source: Internet
Author: User

Http://www.codeproject.com/Tips/397574/Use-Csharp-to-get-JSON-Data-from-the-Web-and-Map-i

Introduction

This tip/trick demonstrates a complete and easy solution on how to getJSONFormatted data from a Web service, and map (deserialize) it to custom. Net classFor further usage.

As an example, we will use http://openexchangerates.org site which provides latest currency rates formattedJSONData. Latest daily rates will be retrieved from this here.

It outputs currency data in the followingJSONFormat:

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 throughC #On the server side and use them? Read on to find out.

How to-three easy stepsstep 1. Install JSON. Net Library

JSON. netLibrary provides an easy, andDe-facto, Standard way to convert (Serialize). NetClassJSONData, andJSONData back. NetClass (Deserialize).

The easiest way to installJSON. netLibrary into your. NetProject 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 usingVisual Studio 2012You're in luck, since you can just paste a sampleJSONData and it will create a class for you, to do that, first create a new class. CSFile, select it in project explorer, than copy sampleJSONData to clipboard, goEdit> 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. NetClass manually. It must exactly match the formatJSONData provided to us by http://openexchangerates.org/latest.json:

Collapse | Copy code
 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 matchJSONOne. Also, notice how"Rates" JSONProperty is matched toDictionary <string, decimal>. If"Rates"Wocould have a singular value, they cocould alternatively be matched toArrayOrIenumerable.

 

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. NetClass, where'T'Represents any. NetClass that you needJSONData to be mapped:

Collapse | Copy code
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 instanceWebClient () System. netClass (a part of. Net) Downloads data from the specific URL (http://openexchangerates.org/latest.json in our case) as a plainString.

Then, thisStringContainingJSONData is mapped (deserialized) to any. NetClass provided (CurrencyratesIn our case ).

Deserialization is doneJSON. netLibrary's MethodJsonconvert. deserializeobject <t> (json_data), Which attempts to match allJSONFields to the same. NetClass fields.

In this example, a call to a universal method_ Download_serialized_json_data <t> ()Can look like this:

Collapse | Copy code
 
VaRUrl ="Http://openexchangerates.org/latest.json";VaRCurrencyrates = _ 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

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.