2

I need to get currency values list in C# from here: http://openexchangerates.org/currencies.json

which produces this kind of output:

{
    "AED": "United Arab Emirates Dirham",
    "AFN": "Afghan Afghani",
    "ALL": "Albanian Lek",
    "AMD": "Armenian Dram",
    "ANG": "Netherlands Antillean Guilder",
    "AOA": "Angolan Kwanza"
        // and so on
}

I managed to get a string containing values above using C#, but I cannot find a way to deserialize that string into any custom class or anonymous object, so I am wondering how to do that?

Also, I am trying to use Json.NET to do that, but so far couldn't find a solution...

mikhail-t
  • 4,103
  • 7
  • 36
  • 56

2 Answers2

5

using Json.Net

var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonString);

--EDIT--

You can make it shorter

WebClient w = new WebClient();
string url = "http://openexchangerates.org/currencies.json";
var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(w.DownloadString(url));
L.B
  • 114,136
  • 19
  • 178
  • 224
  • I found that a second ago myself, I posted my own answer without knowing that I got responses already)) Thanks anyway! – mikhail-t May 09 '12 at 20:45
  • 1
    @LB - Wow! That is awesome! Much better than mine! Thank you so much! I deleted my answer since it is redundant now. – mikhail-t May 09 '12 at 21:37
2

A solution using only .Net 4.0 and no third party libraries:

string url = "http://openexchangerates.org/currencies.json";

var client = new System.Net.WebClient();
string curStr = client.DownloadString(url);

var js = new System.Web.Script.Serialization.JavaScriptSerializer();
var res = (js.DeserializeObject(curStr) as Dictionary<string, object>)
    .Select(x => new { CurKey = x.Key, Currency = x.Value.ToString() });

Outputs a list of anonymous objects with the keys and values from the list as properties.

Enjoy :)

lerager
  • 31
  • 2
  • 1
    Thanks! Good to know the other way around this! Our company will continue to use Json.Net though - the main reason is that it became so mainstream and stable, that it will be eventually included into the MVC 4: http://aspnet.codeplex.com/wikipage?title=ASP.NET%20MVC%204%20RoadMap (look at "What's Next?" section) – mikhail-t May 10 '12 at 14:13