如何在 Xamarin Forms 中使用 cryptocompare API

How to use cryptocompare API with Xamarin Forms

您好,我正在尝试制作一个显示不同加密货币汇率的 Xamarin 应用程序。为此,我决定使用 CryptoCompare API。我有这样的数据模型:

public class Coin
{
    public float Price { get; set; }
    public string Currency { get; set; }

    public string USD { get; set; }

}

这就是我调用 API

的方式
public class DataService
{
    HttpClient client = new HttpClient();
    public DataService()
    {

    }
    public async Task<List<Coin>> GetCoinsAsync()
    {
        var response = await client.GetAsync("https://min-api.cryptocompare.com/data/price?fsym=XRP&tsyms=USD,BTC");

            var content = await response.Content.ReadAsStringAsync();
            var Coins = JsonConvert.DeserializeObject<List<Coin>>(content);
            return Coins; 
    }
}

通过调试,我意识到虽然内容变量包含 API 数据 ({"NZD":3.89,"BTC":0.0001567}),但 Coins 变量保持为空。 问题出在这一行

var Coins = JsonConvert.DeserializeObject<List<Coin>>(content);

我收到一条错误消息

Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current 
JSON object (e.g. {"name":"value"}) into type 
'System.Collections.Generic.List`1[Crypto.Models.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 'USD', line 1, position 7.

我知道它告诉我如何修复它,但我不确定如何修复它。有什么帮助吗?谢谢

检查您从服务获得的响应并更正您的模型。

为什么单件退货还期待合集?

下次您必须处理 JSON 并且想要快速生成 C# 模型时,请使用 https://app.quicktype.io 等服务。现在只需为您的 类.

起一个合乎逻辑的名称
// To parse this JSON data, add NuGet 'Newtonsoft.Json' then do:
//
//    using QuickType;
//
//    var data = Welcome.FromJson(jsonString);

namespace QuickType
{
    using System;
    using System.Net;
    using System.Collections.Generic;

    using Newtonsoft.Json;

    public partial class Welcome
    {
        [JsonProperty("USD")]
        public double Usd { get; set; }

        [JsonProperty("BTC")]
        public double Btc { get; set; }
    }

    public partial class Welcome
    {
        public static Welcome FromJson(string json) => JsonConvert.DeserializeObject<Welcome>(json, Converter.Settings);
    }

    public static class Serialize
    {
        public static string ToJson(this Welcome self) => JsonConvert.SerializeObject(self, Converter.Settings);
    }

    public class Converter
    {
        public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
        {
            MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
            DateParseHandling = DateParseHandling.None,
        };
    }
}