Im trying to get a cryptocurrency last price value from a HTTP API:
The following piece of code:
// Create the web request
HttpWebRequest request =
WebRequest.Create("APISITE") as
HttpWebRequest;
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
// Console application output
currentXRPPrice.Text = (reader.ReadToEnd());
}
Gives me the following response which is correct:
{"high": "1.15600", "last": "1.08269", "timestamp": "1518697359", "bid": "1.08034", "vwap": "1.09634", "volume": "40858340.75727354", "low": "1.03051", "ask": "1.08269", "open": "1.13489"}
What I want is just the value of "last" which is "1.08269".
I have tried using this post: [link] (Remove characters after specific character in string, then remove substring?)
which has worked wonders for me on previous projects. But I cant seem to figure out where I am going wrong.
Iv tried below to get the value of "last" but its completely wrong, I have tried many of the different combinations to get it right but its not working to show me just the value for "Last".
response = currentXRPPrice.Text;
response = response.Remove(response.LastIndexOf(":") + 1);
profitLossText.Text = response; //Still wrong tried 4 combinations none work.
Thanks for any help!
You need to install Newtonsoft.Json from Nuget packages and use Parse method from JObject:
var lastValue = JObject.Parse(currentXRPPrice.Text).SelectToken("last").ToString();
First of all, if you have Json string, you can define a class which represent this object and then you just deserialize this string to object using generic method.
var jsonString = currentXRPPrice.Text;
var deserializedResponse = JsonConvert.DeserializeObject<ReponseType>(jsonString);
var lastValue = deserializedResponse.Last;
public class ReponseType
{
...
public float Last { get; set; }
...
}
You can do it by Regex too:
var lastValue = Regex.Match(jsonString, #"last\": \"(\\d+\\.\\d+)"").Groups[0];
Related
This question already has answers here:
Deserialize JSON data with C#
(4 answers)
Closed 1 year ago.
I am a student working on a project. I am trying to use the Yahoo! Finance API as a source for my data https://www.yahoofinanceapi.com . I can use HttpWebRequests to call the API and get the "OK" code, see the code below on how I did it:
string BaseURL = "https://yfapi.net/v6/finance/quote?symbols=AAPL";
string addSymbol = "%2C";
string URL = BaseURL;
foreach (string stock in stocks)
{
URL += addSymbol + stock;
}
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Headers.Add("X-API-KEY", "[My API key]");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Console.WriteLine(response.ContentType);
Console.WriteLine(response.StatusCode);
response.ContentType gives back "application/json".
response.StatusCode gives back "OK".
Since the response is a JSON I tried to parse it into a string using .ToString() but this obviously doesn't work. When I print it, it just says "System.Net.HttpWebResponse" instead of the showing the actual data in the JSON.
After that I tried to deserialize it using newtonsoft
Results result = JsonConvert.DeserializeObject<Results>(request.GetResponse().ToString());
where Results is a class I made where there is a list of stocks, Stock is also a class I made with some variables in it with the same names of variables in the JSON response.
I got a JSON response from PostMan when I tested the API, opened the response to see what kind of data it contained.
When I ran my code I got the following error message:
Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered while parsing value: S. Path '', line 0, position 0.'
This was as far as I got, I tested a few other methods trying to get this working but this one worked the "best".
My biggest issue at the moment is mapping the response into a c# object.
Anything that can help me understand is appreciated :D
You're trying to serialise the HttpWebResponse object into Results, which means deserialisation won't work.
The data is still wrapped & won't be in the format of the Results object.
The GetResponseStream() method can be used to get the contents of the HTTP response as a stream, which can then be deserialised directly, in this case, using Json.NET.
Replace this section:
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Console.WriteLine(response.ContentType);
Console.WriteLine(response.StatusCode);
With this:
var serializer = new JsonSerializer();
using (var response = (HttpWebResponse)request.GetResponse())
{
var encoding = Encoding.GetEncoding(response.CharacterSet);
using var responseStream = response.GetResponseStream();
using var reader = new StreamReader(responseStream, encoding);
using (var jsonTextReader = new JsonTextReader(reader))
{
Console.WriteLine(response.ContentType);
Console.WriteLine(response.StatusCode);
Results result = serializer.Deserialize<Results>(jsonTextReader);
}
}
Alternatively, a much better solution if you're using .NET 4.5 <= would be to use HttpClient like below:
private static readonly HttpClient httpClient = new HttpClient();
...
string BaseURL = "https://yfapi.net/v6/finance/quote?symbols=AAPL";
string addSymbol = "%2C";
string URL = BaseURL;
foreach(string stock in stocks) {
URL += addSymbol + stock;
}
client.DefaultRequestHeaders.Add("X-API-KEY", "[My API key]");
var data = await httpClient.GetStringAsync(address);
Results result = JsonConvert.DeserializeObject<Results>(data);
My code here to get data from Wikipedia:
string URL = $"https://en.wikipedia.org/w/api.php?action=query&format=json&list=&titles={query}&redirects=1";
WebRequest wrREQUEST;
wrREQUEST = WebRequest.Create(URL);
wrREQUEST.Proxy = null;
wrREQUEST.Method = "GET";
WebResponse response = wrREQUEST.GetResponse();
StreamReader streamReader = new StreamReader(response.GetResponseStream());
string responseData = streamReader.ReadToEnd();
JObject jsonData = JObject.Parse(responseData);
var jsonQuery = jsonData["query"];
string pageID = (string)jsonQuery;
But I keep getting
Exception thrown: 'System.ArgumentException' in Newtonsoft.Json.dll
and the json data looks like this:
{
"batchcomplete":"",
"query":{
"pages":{
"31717":{
"pageid":31717,
"ns":0,
"title":"United Kingdom"
}
}
}
}
I also want to know since "pages":{"31717":{}} is an ID which I will not know in advance, how can I get that 31717 from enumerating the data?
The error is because you are trying to explicitly convert JObject into a string, which is not possible using conversion, only by using Serilization.
But I understand you actually want the "PageId", which by the json structure, look like you need to take the "first key" from the response.
(Actually there are more ways)
So instead of
string pageID = (string)jsonQuery;
One possible way, will be using this
((JProperty)jsonQuery["pages"].First()).Name
Please find resolution of yout request, it might be possible that some time u will not get the first element value and it will trigger some exception.
Please replace your line :
string pageID = (string)jsonQuery;
with
**var jToken = jsonQuery["pages"].First;
if (jToken != null)
{
string pageID = ((JProperty) jToken).Name;
}**
Trying to deserialize objects from HTTP response.
Response stream returns information in json and I already checked if it is valid in online deserializer.
I got the object class from the API framework so I think all of the properties should be configured for the response.
Code:
var request = new HttpRequestMessage(HttpMethod.Get,
"api_url");
var client = _clientFactory.CreateClient();
var response = await client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
using var responseStream = await response.Content.ReadAsStreamAsync();
var reponseString = await response.Content.ReadAsStringAsync();
var data = await JsonSerializer.DeserializeAsync<IEnumerable<Tournament>>(responseStream);
}
else
{
GetBranchesError = true;
}
I see that information in responseString is correct but data objects are always null.
Weird part is that it partially works because it shows how many objects are in the responseStream but all of the object properties are nulls.
Also tried to set the stream position to 0 - didn't help.
Any idea what I am doing wrong to deserialize these objects?
Desirializer used - System.Text.Json;
Project asp .net core 3.1
The problem is that the properties you are looking for in the JSON array are actually wrapped inside an object called "tournament". It's easier to notice when you format the JSON string nicely like this for example:
[
{
"tournament": {
"id": 1,
"name": "name1",
...
}
},
{
"tournament": {
"id": 2,
"name": "name2",
...
}
}
]
To deserialize this I would suggest you make a wrapper class to handle that:
public class TournamentItem
{
[JsonPropertyName("tournament")]
public Tournament Tournament { get; set; }
}
And then deserialize to that class:
var data = await JsonSerializer.DeserializeAsync<IEnumerable<TournamentItem>>(responseStream);
Now data.Tournament will contain all the properties.
There might still be a few issues in your properties like Spam for example. The JSON string has a null as value, but the property is not nullable - I didn't check all your properties. DeserializeAsync will throw an error and tell you.
I have a file I got from a site that lists all textures and all names. I want to parse the JSON file and get just the name and texture parts get the url property and download the link with the name above.
I'm not sure how to get this because the whole file is large but I just want to get the url and the width and height. If they are 2048 or 4042. If they match get the name and download the URL and give the name value to the name of download.
So in summary
"name": "Metal_2_roughness.jpg",
"images": [
{
"height": 2048,
"createdAt": "2017-08-11T16:14:06.933292",
"updatedAt": "2017-08-11T16:14:06.933307",
"uid": "ae19ea6db7074248ac4e04b4db971913",
"width": 2048,
"options": {},
"url": "https://media.sketchfab.com/urls/cbfbf4d275c24eafa51eaf3a6c3c91b9/dist/textures/16fb95f74f4846079a32f15c2be35565/ae19ea6db7074248ac4e04b4db971913.jpeg",
"size": 1042057
},
If the height and width matches 2048 then check the name. Copy that then copy url and download the URL and give it the name property. But I'm not sure how to go about doing this as I never touched on JSON before.
https://paste.md-5.net/vecaxacafe.bash
Use WebRequest to request url for json and use Json.net to parse the response.
WebRequest webRequest = WebRequest.Create("your url");
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
Console.WriteLine(response.StatusDescription);
if (response.StatusDescription == "OK")
{
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
// Display the content.
dynamic stuff = JObject.Parse(responseFromServer);
Console.Write(stuff.results);
//Iterate over images using a loop
//Condition to check if height and width are same Eg: responseFromServer.images.height == responseFromServer.images.width
// Store the url in a variable like String url = responseFromServer.images.url
}
Hope this helps
Use json2csharp to convert the contents of your file to classes.
Then read the contents with File.ReadAllText() and deserialize the content with Json.NET like this var json = JsonConvert.DeserializeObject<RootObject>(content);
Then you can access the image height via json.images[0].height
If you are getting only a couple of fields from the entire JSON file, then the easiest way is to simply use JSON.NET and use the JObject method.
First install the Newtonsoft.Json Nuget Package.
Then, you can do something as simple as :
var myJsonString = File.ReadAllText("myfile.json");
var myJObject = JObject.Parse(myJsonString);
myJObject.SelectTokens("results[*].images[*].url").Values<string>();
Which will get you all URLs as strings. You may instead prefer to deserialize the entire JSON to an object using the JsonConvert method.
More Info : https://dotnetcoretutorials.com/2019/09/11/how-to-parse-json-in-net-core/
To do what MindingDate, suggested in his answer, in Text.Json you can utilize the JsonDocument class like so:
var myJsonString = File.ReadAllText("myfile.json");
var myJDoc = JsonDocument.Parse(myJsonString);
myJDoc.GetProperty("images")[*].GetProperty("url").ToString();
Can you please give me a sample example of how to make the JSON request body in C#. I am using Visual Studio 2015. I know SOAP UI, but I am new to C#.
Thanks in advance.
You can try the following
Lets assume you have the following webmethod
public void Webmethod(string parameter)
{
//Do what ever
}
In C# you will do the following to call the webmethod, You require Json.net, Newtonsoft or other Json serializer
var webRequest = WebRequest.Create("http:\\www.somesite.com/path/to/webservice/webservice.asmx/Webmethod");
webRequest.Method = "POST";
webRequest.ContentType = "application/json";
Build a Json object representing the parameters
var jsonobjectrepresentingparameters = new {parameter = "Value"};
Get the Json string using Newtonsoft JsonConvert
var datastring = Newtonsoft.Json.JsonConvert.SerializeObject(jsonobjectrepresentingparameters);
Get the bytes
var bytes = Encoding.ASCII.GetBytes(datastring);
Write the bytes to the request
var requestStream = webRequest.GetRequestStream();
requestStream.Write(bytes, 0,bytes.Length);
Get repsonse
var response = webRequest.GetResponse();
If your Webmethod returned anything like a string, int or other data you can use the following class to deserialize
public class Type<T>
{
public T D { get; set; }
public Type()
{
}
}
You will notice when you work with webservices it returns a json object with property d as the value which is why you require the above class in C#
Then you will require the following extra two lines if your return type was string
var json = (new StreamReader(response.GetResponseStream())).ReadToEnd();
var object = JsonConvert.DeserializeObject<Type<string>>(json);