从C#中的Currency Converter API获取汇率

时间:2018-11-16 15:51:12

标签: c# json parsing

这是我的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"是动态的(它的更改取决于待更改的内容),那么如何返回1.140661?

我使用的答案 这是我根据@maccettura注释使用的代码:

var stringResult = await response.Content.ReadAsStringAsync();
var dictResult = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, string>>>(stringResult);
return dictResult[$"{from}_{to}"]["val"];

4 个答案:

答案 0 :(得分:2)

感谢@maccettura。

var stringResult = await response.Content.ReadAsStringAsync();
var dictResult = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, string>>>(stringResult);
return dictResult[$"{from}_{to}"]["val"];

答案 1 :(得分:2)

如果您仍在寻找通过C#中的API获取汇率的解决方案,则可以尝试以下代码:merge

var client = new RestClient("https://api.currencyfreaks.com/latest
    ?apikey=YOUR_APIKEY
    &base=GBP
    &symbols=EUR,USD,PKR,INR");

client.Timeout = -1;

var request = new RestRequest(Method.GET);

IRestResponse response = client.Execute(request);

Console.WriteLine(response.Content);

答案 2 :(得分:0)

使用Newtonsoft.JSON解析后,然后使用JProperty来读取属性。

foreach (JProperty property in data)
{
      Console.WriteLine(property.Name);
      Console.WriteLine(property.Value);
}

答案 3 :(得分:0)

以防万一,我将此解决方案添加到此处,作为通过JValue访问的另一种方式:

   return ((JValue)((JProperty)((JContainer)((JContainer)((JContainer)data).First).First).First).Value).Value.ToString();

我更喜欢@maccettura的答案,因为它更易读。