Get number from API and put it in a variable - c#

I want to get the price value which is usd in this api and put it in a variable:
https://api.coingecko.com/api/v3/simple/price?ids=veco&vs_currencies=usd
I already tried this code but getting an error:
public static void StartGet()
{
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(string.Format(VECO.VecoPriceURL));
WebReq.Method = "GET";
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
string jsonString;
using (Stream stream = WebResp.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8);
jsonString = reader.ReadToEnd();
}
List<VECO.Coin> items = JsonConvert.DeserializeObject<List<VECO.Coin>>(jsonString);
foreach (var item in items)
{
Console.WriteLine(item.usd);
}
}
public class VECO
{
public static string VecoPriceURL = "https://api.coingecko.com/api/v3/simple/price?ids=veco&vs_currencies=usd";
public class Coin
{
public string usd { get; set; }
}
}
ERROR:
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current
JSON object (e.g. {"name":"value"}) into type
'System.Collections.Generic.List`1[ConsoleProgram.VECO+Coin]' because the
type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or
change the deserialized type so that it is a normal .NET type (e.g. not a
primitive type like integer, not a collection type like an array or List<T>)
that can be deserialized from a JSON object. JsonObjectAttribute can also be
added to the type to force it to deserialize from a JSON object.
Path 'veco', line 1, position 8.'

Your Data Structures needs to be slightly different.
public class Veco
{
public decimal usd { get; set; }
}
public class RootObject
{
public Veco veco { get; set; }
}
Please note that Json is a not an array or List, so you need to need List<> in the JsonConvert.DeserializeObject Method as well. Instead, you need to the following.
var result = JsonConvert.DeserializeObject<RootObject>(jsonString);
Example,
var jsonString = #"{'veco':{'usd':0.01558532}}";
var result = JsonConvert.DeserializeObject<RootObject>(jsonString);
Console.WriteLine($"USD Rate : {result.veco.usd}");
Output
USD Rate 0.01558532
Rewriting your method,
public static void StartGet()
{
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(string.Format(VECO.VecoPriceURL));
WebReq.Method = "GET";
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
string jsonString;
using (Stream stream = WebResp.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8);
jsonString = reader.ReadToEnd();
}
var item = JsonConvert.DeserializeObject<RootObject>(jsonString);
Console.WriteLine(item.veco.usd);
}
Update
Based on your comment, I would rewrite your method as follows. You no longer need the data structure.
public static void StartGet(string id)
{
var url = $"https://api.coingecko.com/api/v3/simple/price?ids={id}&vs_currencies=usd";
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(url);
WebReq.Method = "GET";
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
string jsonString;
using (Stream stream = WebResp.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8);
jsonString = reader.ReadToEnd();
}
var result = JsonConvert.DeserializeObject<JToken>(jsonString);
Console.WriteLine($"For {id},USD Rate : {result[id].Value<string>("usd")}");
}
Now you can use the method as follows
StartGet("veco");
StartGet("eos");
StartGet("uraniumx");
Output
For veco,USD Rate : 0.01581513
For eos,USD Rate : 2.42
For uraniumx,USD Rate : 0.890397

Related

String to JSON to 2D Array C#

I am receiving response from httpWebRequest as a string, which is format of JSON. What I would like, is to change this string to json and then, there are two opitons
1) change json to the 2D array
2) change json to dictionary
The point is I want to have easy access to the variables.
This is a string I am receiving:
"[{\"Year\":2000,\"Name\":\"Ala\",\"Val\":0.5},{\"Year\":2001,\"Name\":\"Ola\",\"Val\":0.6}... {\"Year\":2004,\"Name\":\"Ela\",\"Val\":0.8}]"
So as you can see I could have table with n rows and 3 columns (Year, Name, Val).
This is the code which I use to receive the response
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:5000/");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
//send request data in json format
streamWriter.Write(jsonData);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
//take data as string
var result = streamReader.ReadToEnd();
}
return null;
}
Instead of null I will return this array/dictionary.
Which way is better? Someone know how to make it? I feel lost in c#.
Thank you for help in advance!
First, to make work with JSON easier you can install Newtonsoft.Json package
Install-Package Newtonsoft.Json -Version 11.0.2
Then add using Newtonsoft.Json;
Look at this example
public class Item
{
public int Year { get; set; }
public string Name { get; set; }
public double Val { get; set; }
}
public class Program
{
public static void Main()
{
string json = "[{\"Year\":2000,\"Name\":\"Ala\",\"Val\":0.5},{\"Year\":2001,\"Name\":\"Ola\",\"Val\":0.6},{\"Year\":2004,\"Name\":\"Ela\",\"Val\":0.8}]";
List<Item> items = JsonConvert.DeserializeObject<List<Item>>(json);
foreach(var item in items)
{
Console.WriteLine("Year: {0}; Name: {1}; Val: {2}", item.Year, item.Name, item.Val);
}
}
}
Here I create a new class Item witch will be represents one object from array from your JSON. Then using Newtonsoft.Json deserialize json string to list of items.

json to c# deserilization

I want to convert this JSON return from php file into c#. But as a newbie don't know how, please help.
{"response": [
{"user_id":"26","crtloc_lat":"47.678238","crtloc_lng":"-122.131416"},
{"user_id":"27","crtloc_lat":"9.350192","crtloc_lng":"-95.391006"},
{"user_id":"28","crtloc_lat":"47.678238","crtloc_lng":"-122.131416"}
]}
The above JSON is returned from my PHP file.
WebRequest request = WebRequest.Create("http://localhost/abh/returntest.php");
WebResponse response = await request.GetResponseAsync();
List<Response> json ;
using (var stream = new StreamReader(response.GetResponseStream()))
{
json = JsonConvert.DeserializeObject<List<Response>>(stream.ReadToEnd());
}
foreach (var item in json)
{
Console.WriteLine("id={0},latitude={1},longitude={2}",item.user_id,item.crtloc_lat,item.crtloc_lng);
}
The Classes I am using are:
public class Response
{
public string user_id { get; set; }
public string crtloc_lat { get; set; }
public string crtloc_lng { get; set; }
}
public class RootObject
{
public List<Response> response { get; set; }
}
I am getting this error:
Cannot deserialize the current JSON object (e.g. {"name":"value"})
into type 'System.Collections.Generic.List`1[afterall.Response]'
because the type requires a JSON array (e.g. [1,2,3]) to deserialize
correctly.
The following line is wrong based on your sample JSON.
json = JsonConvert.DeserializeObject<List<Response>>(stream.ReadToEnd());
Try changing it to:
json = JsonConvert.DeserializeObject<RootObject>(stream.ReadToEnd());
Edit:
WebRequest request = WebRequest.Create("http://localhost/abh/returntest.php");
WebResponse response = await request.GetResponseAsync();
RootObject json;
using (var stream = new StreamReader(response.GetResponseStream()))
{
json = JsonConvert.DeserializeObject<RootObject>(stream.ReadToEnd());
}
foreach (var item in json)
{
Console.WriteLine("id={0},latitude={1},longitude={2}",item.user_id,item.crtloc_lat,item.crtloc_lng);
}
rewrite the following line :
json = JsonConvert.DeserializeObject<List<Response>>(stream.ReadToEnd());
as
json = JsonConvert.DeserializeObject<Response>(stream.ReadToEnd());
From your testlink in the comment of your post. Your response is not:
{"response": [
{"user_id":"26","crtloc_lat":"47.678238","crtloc_lng":"-122.131416"},
{"user_id":"27","crtloc_lat":"9.350192","crtloc_lng":"-95.391006"},
{"user_id":"28","crtloc_lat":"47.678238","crtloc_lng":"-122.131416"}
]}
as you post but rather:
connected{"response": [
{"user_id":"26","crtloc_lat":"47.678238","crtloc_lng":"-122.131416"},
{"user_id":"27","crtloc_lat":"9.350192","crtloc_lng":"-95.391006"},
{"user_id":"28","crtloc_lat":"47.678238","crtloc_lng":"-122.131416"
}]
}
This is not corresponding to your sample code. Remove the
connected{ }
wrapping or return correct json for a connected object (whatever the connect is). If you remove the wrapping it should work as #Dietz posted.

String Convert to JSON object

I have this code:
public void ProcessRequest(HttpContext context)
{
var jsonSerializer = new JavaScriptSerializer();
var jsonString = String.Empty;
context.Request.InputStream.Position = 0;
using (var inputStream = new StreamReader(context.Request.InputStream))
{
jsonString = inputStream.ReadToEnd();
}
}
Up code get json string and write in jsonString.
jsonString result return
{"id":"54","name":"reza"}
How can i convert jsonString to JsonObject and parse it?
You can use NewtonSoft json library for c# and use below code
Create a class to hold the result
Class Person
{
public int id {get;set;}
public string name {get;set;}
}
var person = JsonConvert.DeserializeObject<Person>(jsonString);
if you dont want to create class use JObject
dynamic newObj = JObject.Parse(jsonString);
string id= newObj.id ;
string name= newObj.name;
Solution 1
Use Newtonsoft.Json (Get package from here https://www.nuget.org/packages/newtonsoft.json/)
using (var inputStream = new StreamReader(context.Request.InputStream))
{
var jsonString = inputStream.ReadToEnd();
var data = JsonConvert.DeserializeObject<Dictionary<string,string>>(jsonString);
return data;
}
Solution 2
Please follow the following Post
http://www.codeproject.com/Tips/79435/Deserialize-JSON-with-C

JSON Numeric Keys

Sorry for asking this question again, but I just don't seem to understand the given answers :(
I need to read some JSON using JSON.net. some of the keys start with numbers, eg.
"24h_rate":22.65826595,"
When I put the JSON into http://json2csharp.com/ to make my classes, it makes it into __invalid_name__24h_total.
I am using the following to read and Deserialize the JSON
public class JsonWebClient
{
public async Task<System.IO.TextReader> DoRequestAsync(WebRequest req)
{
var task = Task.Factory.FromAsync((cb, o) => ((HttpWebRequest)o).BeginGetResponse(cb, o), res => ((HttpWebRequest)res.AsyncState).EndGetResponse(res), req);
var result = await task;
var resp = result;
var stream = resp.GetResponseStream();
var sr = new System.IO.StreamReader(stream);
return sr;
}
public async Task<T> getJsonAsync<T>(string url)
{
HttpWebRequest req = HttpWebRequest.CreateHttp(url);
req.AllowReadStreamBuffering = true;
var ret = await DoRequestAsync(req);
var response = await ret.ReadToEndAsync();
return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(response);
}
}
What do I need to change to make this work?
Thanks very much.
Playing around with it a bit I found out that the deserializer you're using can't 'handle' key names that start with a number for some reason, even though it's perfectly valid JSON (checked with http://jsonlint.com/)
If you change it to this instead
{ "rate_24h":22.65826595 }
it works:
public class RootObject
{
public double rate_24h { get; set; }
}
Thanks to #Ulugbek Umirov:
Your rate_24h property should be attributed with [JsonProperty("24h_rate")] to be property deserialized by JSON.NET.

Deserialize JSON to Dictionary with DataContractJsonSerializer in Windows Phone

I have a json string, for example
{"timestamp":1362463455, "features" : {"one":true, "two":false}}
I want to deserialize it with DataContractJsonSerializer to my class:
[DataContract]
public class MyClass
{
[DataMember(Name = "timestamp")]
public int Timestamp { get; set; }
[DataMember(Name = "features")]
public Dictionary<string, bool> Features { get; set; }
}
But I have a error in process "ArgumentException". I have a problems with deserialize Dictionary, if deserialize only timestamp then I don't have errors. I thought is dictionary most suitable structure for this. But it don't work. I checked this answer on SO, but Dictionary<string, object> don't work too.
Maybe because in example using:
DataContractJsonSerializerSettings settings =
new DataContractJsonSerializerSettings();
settings.UseSimpleDictionaryFormat = true;
But I can't use DataContractJsonSerializerSettings in Windows Phone.
Sorry, if my question is double.
Thank advance.
#Alexandr
I am writing a code for you it will help you to deserialize the object from json to yourClassCustomObject.
private async Task<List<MyClass>> MyDeserializerFunAsync()
{
List<MyClass> book = new List<MyClass>();
try
{
//I am taking my url from appsettings. myKey is my appsetting key. You can write direct your url.
string url = (string)appSettings["mykey"];
var request = HttpWebRequest.Create(url) as HttpWebRequest;
request.Accept = "application/json;odata=verbose";
var factory = new TaskFactory();
var task = factory.FromAsync<WebResponse>(request.BeginGetResponse,request.EndGetResponse, null);
var response = await task;
Stream responseStream = response.GetResponseStream();
string data;
using (var reader = new System.IO.StreamReader(responseStream))
{
data = reader.ReadToEnd();
}
responseStream.Close();
DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(List<MyClass>));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(data));
book = (List<MyClass>)json.ReadObject(ms);
return book;
}
}
Above code is working in my wp8 application it is faster you can try, it will help you. I am performing asynchronous operation but you can create your simple method with MyClass return type.

Categories

Resources