How do I get a JSON object from a webpage - c#

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

Related

How to get data from a nested json in c#

{"data": {"day2": {"mId": "9ilrMdX15S", "votes": "2,893"},"day3": {"mId": "9ilert415S","votes": "2,343"}}}
How can i retrieve the data from a json data as such (i.e the data in "day2", or "day3") i followed the answers here > Appending json data to listview c# by Brain Rogers but the answer only work for json object not for nested json.
Here's an example of how to navigate it:
foreach (JProperty day in JObject.Parse(json)["data"])
{
string name = day.Name;
string id = day.Value.Value<string>("mId");
string votes = day.Value.Value<string>("votes");
}
Thanks for all the response, i was able to solve the task using the SimpleJSON library by Bunny83 GitHub - Bunny83/SimpleJSON: A simple JSON parser in C#
JSONNode data = JSON.Parse(//jsonData or Url//);
string mId = data["data"]["day2"]["mId"].Value;
string votes = data["data"]["day2"]["votes"].Value;

How to parse JSON with Newtonsoft?

I created an ASP.NET Application, where I have to parse a csv file with a json structure.
The csv file itself is structured like:
{"Instance":"abc","Date":"2019-06-03T00:00:02.056Z","Identification":"someFunction","Type":"DurationInMs","Value":"5","iserror":"False""}
I get the jsonCsvData as a string and tried to parse it. Then I want to save some of the elements of this json object into a db.
public IActionResult ReadJsonCsvData(string jsonCsvData)
{
Console.WriteLine("ReadJsonCsvData");
ChartData chartData = new ChartData();
var lines = jsonCsvData.Split("\n");
foreach (var line in lines)
{
var values = JObject.Parse(line);
var first = string.Concat(values["Instance"]); //Output for first: ""
}
}
The problem now is, that the variable first is an empty string. The result should be (like in the json structure example above) "abc".
Thank you in advance!
I don't know if it will help but here is my solution (remove one of " at the end of your Json).
I use the "Jobject" to parse Json as I want. Import this two reference.
using Newtonsoft.Json.Linq;
using Newtonsoft;
Then you have to create your JObject :
JObject o = JObject.Parse(myJsonString);
Then to retrieve specifics data, you just have to search in your object just like you do with a dictionary with key :
instanceFromJson = o["Instance"].ToString;
dateFromJson = o["Date"].ToString;
If you have a table in your "instance" json object you can retrieve all data from this list just like that :
foreach (var item in o["Instance"]["tabFromInstanceObject"])
{
MyList.Add(item);
}

Get property from JSON by string name (already deserialized to class)

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&currencies=" + 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.

How to pass a variable in url in 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

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