Here is my api call:
https://free.currencyconverterapi.com/api/v6/convert?q=EUR_USD&compact=y
I wrote a method that accepts to/from parameters for exchange rates and I successfully get back a result. My problem is parsing that result to get the value. Here is what I have thus far:
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.";
}
}
}
If my data variable = {"EUR_USD":{"val":1.140661}} where "EUR_USD" is dynamic (It changes pending on what to/from is) then how do I return 1.140661?
ANSWER I USED Here is the code I used based off of @maccettura comment:
var stringResult = await response.Content.ReadAsStringAsync();
var dictResult = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, string>>>(stringResult);
return dictResult[$"{from}_{to}"]["val"];