如何在asp.net C#中反序列化这个Json数据。
{"USD_PHP":{"2016-12-31":49.560001},"PHP_USD":{"2016-12-31":0.020178}}
此处USD_PHP
和PHP_USD
将始终是唯一的,日期2016-12-31
对于每个日期值也是唯一的。我想在我的申请中获得货币兑换率(49.560001和0.020178)。如何构建没有公共密钥字段的程序?
答案 0 :(得分:0)
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);
}
}
我希望这个例子可以帮助你。
答案 1 :(得分:0)
反序列化为Dictionary<string, Dictionary<string, decimal>>
。外键将是货币转换名称,内键将是日期,内部值将是转换率。这适用于JavaScriptSerializer
或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);
}
}
输出:
USD_PHP 2016-12-31 49.560001
PHP_USD 2016-12-31 0.020178
小提琴(Json.Net):https://dotnetfiddle.net/L7cvMY