您好我正在尝试制作一个显示不同加密货币率的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.
我意识到它告诉我如何解决它,但我不知道如何解决它。有什么帮助吗?感谢
答案 0 :(得分:1)
检查您从服务中获得的响应并更正您的模型。
为什么在重新调整单个项目时会期望收集?
下次当您必须处理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,
};
}
}