I'm using https://currencylayer.com/documentation , Free account's currency conversion API. I let user input output currency, so for example if user input SGD, It'll display the currency conversion for USD to SGD:"USDSGD":1.318504 The way to grab that value is to use dynamic deserializer, and put it to a label. like so:
lblResult.Text=test.quotes.USDSGD.ToString();
But what I want is to get the result regardless of the user selected currency. The other is always USD so I’d like to combine that and the user input currency to get the correct value from the API, like:
var propertyName = "USD" + destinationCurrencyName; // "USDSGD"
lblResult.Text=test.quotes.{propertyName}; // what I'd like
Here I would access the property "USDSGD".
I know that I can use reflection (Get property value from string using reflection in C#) but that seem to be overkill.
This is what the query returns:
{
"success":true,
"terms":"https:\/\/currencylayer.com\/terms",
"privacy":"https:\/\/currencylayer.com\/privacy",
"timestamp":1517629571,
"source":"USD",
"quotes":{
"USDSGD":1.318504
}
}
This is my code - strongly typed version indeed produces expected result, but I'd like to read name of currency (essentially property name of quotes
element) from text box:
protected void btnConvert_Click(object sender, EventArgs e)
{
string convertTo = TextBox1.Text.ToString();
var webRequest = (HttpWebRequest)WebRequest.Create("http://apilayer.net/api/live?access_key=MY_ACCESS_KEY¤cies=" + Server.UrlEncode(convertTo) + "&source=USD&format=1");
var webResponse = (HttpWebResponse)webRequest.GetResponse();
if (webResponse.StatusCode == HttpStatusCode.OK)
{
JavaScriptSerializer json = new JavaScriptSerializer();
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
var resString = sr.ReadToEnd();
//var test = JsonConvert.DeserializeObject<Result>(resString);
//lblResult.Text=test.quotes.USDSGD.ToString();
var test2 = JsonConvert.DeserializeObject<dynamic>(resString);
lblResult.Text = test2.quotes.USD+convertTo;
}
}
Currently my code
var test2 = JsonConvert.DeserializeObject<dynamic>(resString);
lblResult.Text = test2.quotes.USD+convertTo;
Returns the value:
SGD
Since the "convertTo" Variable happens to be "SGD".
I want the code to execute lblResult.Text = test2.quotes.USD+convertTo;
not return me "convertTo" variable.