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

时间:2019-01-27 02:11:56

标签: 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.'

1 个答案:

答案 0 :(得分:2)

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

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

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

请注意,Json不是数组或List,因此您还需要在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