我想从 API 获取数据 https://rapidapi.com/coinlore/api/coinlore-cryptocurrency/
结果如下:
{2 items
"data":[...]100 items
"info":{...}2 items
}
当我这样看时,我不知道如何创建对象。
我想获取数据数组并创建一个像这样的对象:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace SmartCryptoWorld.Models
{
public class Exchange
{
[JsonProperty("data")]
public List<ExchangeBody> CryptoExchange { get; set; }
}
public class ExchangeBody
{
[JsonProperty("symbol")]
public string Symbol { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("price_usd")]
public double Price { get; set; }
[JsonProperty("percent_change_24h")]
public double Percent_Change_24h { get; set; }
[JsonProperty("percent_change_1h")]
public double Percent_Change_1h { get; set; }
[JsonProperty("percent_change_7d")]
public double Percent_Change_7d { get; set; }
[JsonProperty("market_cap_usd")]
public double Market_Cap_USD { get; set; }
}
}
这是有效的方法,但数据没有进入列表并去捕获异常:
private async Task GetExchange()
{
try
{
var client = new HttpClient();
var request = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri("https://coinlore-cryptocurrency.p.rapidapi.com/api/tickers/?start=0&limit=100"),
Headers =
{
{ "x-rapidapi-host", "coinlore-cryptocurrency.p.rapidapi.com" },
{ "x-rapidapi-key", "51569aba99mshf9e839fcfce791bp16c0dbjsn9ced6dba7472" },
},
};
using (var response = await client.SendAsync(request))
{
var exchange = new Exchange();
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
var exchangeBody = JsonConvert.DeserializeObject<List<ExchangeBody>>(body);
exchange.CryptoExchange = exchangeBody;
}
}
catch (Exception ex)
{
await DisplayAlert("Alert", "Please, check your internet connection.", "OK");
}
}
在
var body = await response.Content.ReadAsStringAsync();
中,我看到来自 API 的数据,当我使用调试器跳到下一行时 var exchangeBody = JsonConvert.DeserializeObject<List<ExchangeBody>>(body);
我看到了 catch 异常..
所以我 100% 确定这些对象不符合其应有的样子?
异常消息是:
ex {Java.Net.UnknownHostException: Unable to resolve host "coinlore-cryptocurrency.p.rapidapi.com": No address associated with hostname ---> Java.Lang.RuntimeException: android_getaddrinfo failed: EAI_NODATA (No address associated with hostname) --- End of inne…}
请求返回的 json 是
object
而不是 list
,您应该将 json 反序列化为 object
而不是 list
。
修改您的代码如下
var exchangeBody = JsonConvert.DeserializeObject<Exchange>(body);
exchange = exchangeBody;