c# - 从 API 获取数字并将其放入变量中

标签 c# asp.net json asp.net-core

我想在这个 api 中获取 usd 的价格值并将其放入一个变量中: https://api.coingecko.com/api/v3/simple/price?ids=veco&vs_currencies=usd

我已经尝试过此代码但出现错误:

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

错误:

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.'

最佳答案

您的数据结构需要略有不同。

public class Veco
{
    public decimal usd { get; set; }
}

public class RootObject
{
    public Veco veco { get; set; }
}

请注意,Json 不是数组或列表,因此您还需要在 JsonConvert.DeserializeObject 方法中使用 List<>。相反,您需要执行以下操作。

var result = JsonConvert.DeserializeObject<RootObject>(jsonString);

例子,

var jsonString = @"{'veco':{'usd':0.01558532}}";
var result = JsonConvert.DeserializeObject<RootObject>(jsonString);
Console.WriteLine($"USD Rate : {result.veco.usd}");

输出

USD Rate 0.01558532

重写你的方法,

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

更新

根据您的评论,我将按如下方式重写您的方法。您不再需要数据结构。

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

现在可以使用如下方法了

StartGet("veco");
StartGet("eos");
StartGet("uraniumx");

输出

For veco,USD Rate : 0.01581513
For eos,USD Rate : 2.42
For uraniumx,USD Rate : 0.890397

关于c# - 从 API 获取数字并将其放入变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54384515/

相关文章:

c# - 是否有一个存储库可以抽象出 Azure、S3 等?

c# - Xamarin 和数据绑定(bind)

c# - Linq2Sql 未在 C# 类中显示

asp.net - 以编程方式添加母版页

c# - 主机与 DnsSafeHost

java - jackson :反序列化空字符串而不是预期对象时为 "Unexpected token (VALUE_STRING), expected FIELD_NAME:"

c# - 尝试使用 JSON.NET 反序列化带有周围 [] 字符的 JSON

javascript - 使用ajax将html表单以json格式发布到Django

java - Genson 多态/通用序列化

c# - linqTOsql 在运行时返回 "specified cast not valid"异常