How to pass a variable in url in c# - c#

I am trying to pass a string into a url in C#:
using (var client = new WebClient())
{
var responseStr = client.DownloadString("http://api.openweathermap.org/data/2.5 /weather?q=Groningen,nl&APPID=%207b030ffcc7338cc5f1adc4ca8e6205aa");
}
I there a way to pass a string variable, instead of ?q=Groningen
So I could use a text field to get the weather of a city.
I could not find the answer.
Thank you

In C# you can use + operator to concatenate strings.
So you can use something like following,
using (var client = new WebClient())
{
var responseStr = client.DownloadString("http://api.openweathermap.org/data/2.5 /weather?q="+CHOICE+",nl&APPID=%207b030ffcc7338cc5f1adc4ca8e6205aa");
}
CHOICE is the variable with your desired location.
More on concatenate : here

You could use string concatenation to do so:
var url = "http://.....q="+city+"&.....";
var responseStr = client.DownloadString(url);
where city is the variable that holds the city you want to pass.

Webclient client = new Webclient();
string city = "Lahore";
string appId = "123456789";
string url = "http://api.openweathermap.org/data/2.5/weather?APPID="+appId+"&q="+city+"";
var json = client.DownloadString(json);
Now de-serialize josn response as per your requirement.
Either using any way below
JavaScriptSerializer
JSON.Net library
DataContractJsonSerializer

Related

Query string of Webclient to json string - c#

I'm using below query for sending data to webAPI. It is working fine. How can I convert the query string that I used , into a json string within this function? Is it possible?
WebClient wc = new WebClient();
wc.Headers.Add("Authorization", "Bearer " + token);
wc.QueryString.Add("unique_id", (checklist_ID.ToString()));
wc.QueryString.Add("Question_no", (QNO.ToString()));
wc.QueryString.Add("Question", t1_question.Text.ToString());
wc.QueryString.Add("Password", t1_password.Text.ToString());
var data = wc.UploadValues(url, "POST", wc.QueryString);
//here I want this Querystring data in below json format
// [{"unique_id":"2233","Question_no":"43","Question":"XXXX??","Password":"testpswd"}]
var responseString = UnicodeEncoding.UTF8.GetString(data);
Use Linq and JsonConvert to get the desired result
//Use LINQ to convert the QueryString to Dictionary
var keyValuePairs = (
from key in wc.QueryString.AllKeys
from value in wc.QueryString.GetValues(key)
select new { key, value }).ToDictionary(x => x.key, x => x.value);
//Use Newtonsoft.Json to Serialize the object to json format
Console.WriteLine(JsonConvert.SerializeObject(keyValuePairs));

How do I get a JSON object from a webpage

New to C#. I have a URL https://osu.ppy.sh/beatmapsets/781509#osu/1642274
with multiple json objects but I want to retrieve only the object with id="json-beatmapset" from this URL. This is my current piece of code:
string url = #"https://osu.ppy.sh/beatmapsets/781509#osu/1642274";
var code = new WebClient().DownloadString(url);
Console.WriteLine(code);
And I want to be able to extract information (for example the title) from this one json object using this:
dynamic dobj = JsonConvert.DeserializeObject<dynamic>(json);
string title = dobj["title"].ToString();
Console.WriteLine(title);
where json is the json object, which should print
Black Rover (TV Size)
How do I get the json object from this url?
As per my comment, you can use regular expressions to parse string data.
var json = Regex.Match(code, "<script id=\"json-beatmapset\".*?>(.*?)<\\/script>", RegexOptions.Singleline).Groups[1].Value;
dynamic dobj = JsonConvert.DeserializeObject<dynamic>(json);
string title = dobj["title"].ToString();
Console.WriteLine(title);

C# Concatenate URL with 2 or more strings in between the url

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;
}

Getting Nested json element returns an error

I'm trying to a make an application that interacts with the randomuser.me API
but this always returns some kinda of error, this time i'm using a code that i've found in stackoverflow to parse the json content.
So here is my code rightnow:
public string GetJsonPropertyValue(string json, string query)
{
JToken token = JObject.Parse(json);
foreach (string queryComponent in query.Split('.'))
{
token = token[queryComponent];
}
return token.ToString();
}
string getName()
{
string name = "";
try
{
using (WebClient wc = new WebClient())
{
var json = wc.DownloadString("https://randomuser.me/api/");
name = GetJsonPropertyValue(json, "results[0].name.first");
return name;
}
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
return name;
}
}
I don't really know what's the exact problem but it's returning a System.NullReferenceException
EDIT
If i don't insert the index in the second parameter of the GetJsonPropretyValue group method, and insert it this way results.name.first
It returns such an error:
System.ArgumentException: Accessed JArray values with invalid key value: >"name". Array position index expected.
at Newtonsoft.Json.Linq.JArray.get_Item(Object key)
Trying to split the JSON path on dots like you are doing isn't going to work when you have an array index in the path. Fortunately, you don't have to roll your own query method; the built-in SelectToken() method does exactly what you want:
using (WebClient wc = new WebClient())
{
var json = wc.DownloadString("https://randomuser.me/api/");
JToken token = JToken.Parse(json);
string firstName = (string)token.SelectToken("results[0].name.first");
string lastName = (string)token.SelectToken("results[0].name.last");
string city = (string)token.SelectToken("results[0].location.city");
string username = (string)token.SelectToken("results[0].login.username");
...
}
Fiddle: https://dotnetfiddle.net/3kh0b0

How to Parse Json data to normal data in C#

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);

Categories

Resources