【发布时间】:2018-11-16 15:51:12
【问题描述】:
这是我的 api 调用:
https://free.currencyconverterapi.com/api/v6/convert?q=EUR_USD&compact=y
我写了一个方法,接受到/从汇率参数,我成功地得到了一个结果。我的问题是解析该结果以获取值。到目前为止,这是我所拥有的:
public async Task<string> GetExchangeRate(string from, string to)
{
//Examples:
//from = "EUR"
//to = "USD"
using (var client = new HttpClient())
{
try
{
client.BaseAddress = new Uri("https://free.currencyconverterapi.com");
var response = await client.GetAsync($"/api/v6/convert?q={from}_{to}&compact=y");
var stringResult = await response.Content.ReadAsStringAsync();
dynamic data = JObject.Parse(stringResult);
//data = {"EUR_USD":{"val":1.140661}}
//I want to return 1.140661
//EUR_USD is dynamic depending on what from/to is
return data.?????.val;
}
catch (HttpRequestException httpRequestException)
{
Console.WriteLine(httpRequestException.StackTrace);
return "Error calling API. Please do manual lookup.";
}
}
}
如果我的数据变量 = {"EUR_USD":{"val":1.140661}} 其中 "EUR_USD" 是动态的(它会根据 to/from 进行更改),那么我如何返回 1.140661?
我使用的答案 这是我根据@macchettura 评论使用的代码:
var stringResult = await response.Content.ReadAsStringAsync();
var dictResult = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, string>>>(stringResult);
return dictResult[$"{from}_{to}"]["val"];
【问题讨论】:
-
反序列化为
Dictionary<string, Dictionary<string, decimal>>