Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get number from API and put it in a variable

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.'
like image 508
aria darkkkis Avatar asked Mar 28 '26 06:03

aria darkkkis


1 Answers

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
like image 154
Anu Viswan Avatar answered Mar 29 '26 18:03

Anu Viswan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!