How to Deserialize this Json Data in asp.net C#.
{"USD_PHP":{"2016-12-31":49.560001},"PHP_USD":{"2016-12-31":0.020178}}
Here the USD_PHP
and PHP_USD
is going to be always unique, the Date 2016-12-31
is also unique for every date value. All i want to get the Currency Conversion Rate (49.560001, and 0.020178) in my application. How can i Build the program which is having no Common Key Field?
var req = new RestRequest("api url"); // RestSharp.dll
var client = new RestClient("host url");
var response = client.ExecuteTaskAsync(req).Result.Content;
var json =((dynamic)JsonConvert.DeserializeObject(response))
//Newtonsoft.Json.dll
var dic = new Dictionary<string, List<Tuple<string, string>>>();
foreach (var item in json)
{
var items = new List<Tuple<string, string>>();
foreach (var value in item.Value)
{
var newItem = new Tuple<string, string>(value.Name, value.Value.ToString());
items.Add(newItem);
}
if (items.Any())
{
dic.Add(item.Name, items);
}
}
I hope this example will help you.
Deserialize to a Dictionary<string, Dictionary<string, decimal>>
. The outer key will be the currency conversion name, the inner key will be the date, and the value of the inner will be the conversion rate. This will work with either JavaScriptSerializer
or Json.Net .
string json = @"{""USD_PHP"":{""2016-12-31"":49.560001},""PHP_USD"":{""2016-12-31"":0.020178}}";
var jss = new JavaScriptSerializer();
var outer = jss.Deserialize<Dictionary<string, Dictionary<string, decimal>>>(json);
foreach (var kvp in outer)
{
foreach (var kvp2 in kvp.Value)
{
Console.WriteLine(kvp.Key + " " + kvp2.Key + " " + kvp2.Value);
}
}
Output:
USD_PHP 2016-12-31 49.560001
PHP_USD 2016-12-31 0.020178
Fiddle (Json.Net): https://dotnetfiddle.net/L7cvMY
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.