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.
Now that I understand your question, you’re trying to concatenation string for accessing a value, not concatenation value and currency.
This can’t be done with dynamic and there’s no need. Deserialize to JObject and use its properties to get the values:
var test2 = JObject.Parse(resString);
var value = (test2[“quotes”] as JObject)[“USD” + convertTo];
Note that this doesn’t check that the data is valid. value is a JToken you can get the value from.
You will want to use JObject to go through the response object:
var response = JObject.Parse(resString);
var quotes = response["quotes"];
lblResult.Text = quotes[ "USD" + convertTo ].Value<string>().ToString();
The indexers of JObject allow you to index directly by strings, which gives you the ability to dynamically select the correct property the users wants.
Related
How should I get the value of status key ?
string a = "\"[{\\\"Status\\\":\\\"Passed\\\"}]\""
tried with JObject.Parse and JArray.Parse to deserialize it and fetch the value.
getting error all the time, even if the key is present.
PS: this value is coming directly from the DB, where it is stored as a string.
using System.Text.Json;
string a = "\"[{\\\"Status\\\":\\\"Passed\\\"}]\"";
var json = JsonDocument.Parse(a).RootElement.GetString();
var jDoc = JsonDocument.Parse(json);
var dic = jDoc.RootElement[0].Deserialize<Dictionary<string, string>>();
var status = dic["Status"];
Maybe there is a better solution. But you can remove the / character and split by "
string a = "\"[{\\\"Status\\\":\\\"Passed\\\"}]\"";
var val=a.Replace("\\", "").Split(new string[] { "\"" },
StringSplitOptions.None)[4];
Here is a method can get the value, hope it can give you some help.
using Newtonsoft.Json;
string a = "\"[{\\\"Status\\\":\\\"Passed\\\"}]\"";
var b = JsonConvert.DeserializeObject(a);
var c = JsonConvert.DeserializeObject<Dictionary<string, string>[]>(b.ToString());
trying to get a list of dates, I need to add 2 strings in between the URL
Cant concatenate the URL right
Need help deserializing into a DateTime list
public async Task<List<DateTime>>GetDate()
{
// Original Url http://local:8796550/serv/newobj/v678/object/35b724c5424/serv/addIDinhere/dates .
List<DateTime> dates = new List<DateTime>();
var Id= "xxxxxxxxxxxxxxhola57a";
var Uri = "http://local:8796550/serv/newobj/v678/object/35b724c5424/serv/";
var Date="/dates";
var client = new HttpClient();
var ServicesDateRequest = await client.GetAsync($"{Uri}&={Id}&={Date}");
string oj = await ServicesDateRequest.Content.ReadAsStringAsync();
//here deserialized it into datetime list
var DatesJson = JsonConvert.DeserializeObject<dates>(oj);
return dates;
}
When you're using string interpolation you only need the curly braces and the expression. The "&=" that you're adding between each component is unnecessary to get to the url format you're looking for (assuming that the format you want is what the "Original Url" comment shows).
var ServicesDateRequest = await client.GetAsync($"{Uri}{Id}{Date}");
For deserialization, check out the documentation on the method you're using. Specifically, the part about Type Parameters. JsonConvert.DeserializeObject<T>(string).
Type Parameters
T
The type of the object to deserialize to.
In other words, you should be using the type that you want to deserialize (in this case List<DateTime> rather than the name of a variable.
Try this. You can use string.format to format your url with query string paramteres.
Do Deserialize, you need to use type no data.
public async Task<List<DateTime>> GetDate()
{
// Original Url http://local:8796550/serv/newobj/v678/object/35b724c5424/serv/addIDinhere/dates .
List<DateTime> dates = new List<DateTime>();
var Id = "xxxxxxxxxxxxxxhola57a";
var Date = "/dates";
var client = new HttpClient();
var formatedUrl = string.Format("http://local:8796550/serv/newobj/v678/object/35b724c5424/serv/?id={0}&date={1}", Id, Date);
var ServicesDateRequest = await client.GetAsync(formatedUrl);
string oj = await ServicesDateRequest.Content.ReadAsStringAsync();
//here deserialized it into datetime list
var DatesJson = JsonConvert.DeserializeObject<DateTime>(oj);
return DatesJson;
}
I am trying to Parse Json in C# . (I am beginner in Json)
WebRequest webRequest = WebRequest.Create(url);
var httpWebRequest = (HttpWebRequest)webRequest;
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
String responseText = "";
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
responseText = streamReader.ReadToEnd();
}
//
This is Output in responseText :
{
"disclaimer": "Exchange rates provided for informational purposes only and do not constitute financial advice of any kind. Although every attempt is made to ensure quality, no guarantees are made of accuracy, validity, availability, or fitness for any purpose. All usage subject to acceptance of Terms: https://openexchangerates.org/terms/",
"license": "Data sourced from various providers; resale prohibited; no warranties given of any kind. All usage subject to License Agreement: https://openexchangerates.org/license/",
"timestamp": 1454497211,
"base": "EUR",
"rates": {
"INR": 74.42686146,
"USD": 1.0929332
}
}
To get the base from Json
var obj = JObject.Parse(responseText);
String bcur = (string)obj["base"];
Console.WriteLine("base :"bcur.ToString());
Output : base :EUR
similarly to get Rates of INR , I wrote
var obj = JObject.Parse(responseText);
String rte= (string)obj["INR"];
Console.WriteLine("rate:"rte);
it gives me null.
Can anyone tell me what is wrong in my code. or a better way to get the base and rate of the currency .
INR is not in the base object, so you are looking for the INR property in a place where it doesn't exist. You would have to go about it in a two step fashion in order to access the property in . Modifiying your code above, it would look something like this:
var obj = JObject.Parse(responseText);
JObject rates = (JObject)obj["rates"];
string rte = (string)rates["INR"];
Console.WriteLine("rate:" + rte);
I have a list of values in an array Cmnts like
"6_12_g2_text":"22","6_12_g3_text":"33","6_12_g4_text":"44"
var CmntsValue = forms["textvalue"];
string[] Cmnts = CmntsValue.Split('{','}');
No I want to search for 6_12_g2_text and return 22 (for 6_12_g3_text and return 33). How can i achieve this?
I got the value as shown in following image!
I insert my updated code here [in second image]. Kindly check with that
The value you have is actually a JSON string. Using Json.NET you can easily parse the string into a Dictionary<string, int>, like so:
var json = "{\"6_12_g2_text\":\"22\",\"6_12_g3_text\":\"33\",\"6_12_g4_text\":\"44\"}";
var dictionary = JsonConvert.DeserializeObject<Dictionary<string, int>>(json);
And then extract any value by key:
int value;
if (dictionary.TryGetValue("6_12_g2_text", out value))
{
Console.WriteLine(value);
}
Edit:
After seeing your actual JSON string, you're going to have to do some additional work:
var json = "{\"1_3_g1_text\":\"11\"}
{\"1_3_g2_text\":\"\"}
{\"6_12_g2_text\":\"test\"}
{\"6_12_g3_text\":\"\"}
{\"1_17_g1_text\":\"works\"}
{\"5_19_g2_text\":\"submitted\"}
{\"5_19_g3_text\":\"2\"}";
var jsons = json.Split('{', '}').Where(x => !string.IsNullOrWhiteSpace(x));
var concatenatedJson = string.Format("{{{0}}}", string.Join(",", jsons));
var intermidiateDict = JsonConvert.DeserializeObject<Dictionary<string, string>>(
concatenatedJson);
I am beginner in c#, I have output from the website like {"result":"Invalid"} with my c# program, It seems to be Json ,I want to display these data as normal string and display it in message box and use those parsed data for validation
Program:
private async void Button_Click(object sender, RoutedEventArgs e)
{
var username = Username.Text;
var password = passbox .Password;
var postMessage = new StringContent(string.Format("username={0}&password={1}", username, password), Encoding.UTF8 , "application/x-www-form-urlencoded");
var response = await (new HttpClient()).PostAsync("http://xxx.xx.net/xx.php", postMessage);
var responseBody = await response.Content.ReadAsStringAsync();
MessageBox.Show( responseBody );
}
I want to know how to display the responseBody as normal string ?
Ideal solution depends on how complex Json string you got. If it has only single property-value pair like posted in question :
{"result":"Invalid"}
I think simple string manipulation logic will bring you the value ("Invalid") easily. Like this naive code :
var jsonString = "{\"result\":\"Invalid\"}";
//remove "{" and "}" from sting
var result = jsonString.Replace("{", "").Replace("}", "");
//separate property name from it's value
var pair = result.Split(':');
//property will contain property name : "result"
var property = pair[0];
//value will contain property value : "Invalid"
var value = pair[1];
Otherwise, if JSON response is more complex, it is not reliable to use string manipulation. I'd suggest to go with Newtonsoft.Json library as also suggested by #Mohammad.
Try using JSON.Net using below code if it returns result as output then
string json = responseBody;
JObject parsed = JObject.Parse(json);
string results = (string)parsed["result"];
Not too sure if this is the best approach... But I'm currently implementing something similar, and using a reader to... read the returned data.
System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream());
string outputStr = reader.ReadToEnd();
To convert JSON object to string you should serialize it.
I'm using Newtonsoft.Json
After install above package you can use it as the following :
string jsonInString = JsonConvert.SerializeObject(responseBody);
MessageBox.Show(jsonInString);
And for convert json string to an object you can use the following :
ClassName obj = JsonConvert.DeserializeObject<ClassName>(jsonInString);