【发布时间】:2022-01-21 17:34:12
【问题描述】:
我想从https://rapidapi.com/coinlore/api/coinlore-cryptocurrency/的API获取数据
结果如下:
{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…}
【问题讨论】:
-
异常(在
ex)说什么? -
Ben,在公共网站上发布您的秘密(如 API 密钥)不是一个好主意。这里可以是很棒的社区,但有人可以利用这一点。因此,请编辑您的代码并删除该 API 密钥
-
不是
bodyExchange吗?所以你应该反序列化JsonConvert.DeserializeObject<Exchange>(body);而不是List<ExchangeBody>? -
首先,您可以在浏览器中或使用任意数量的免费工具查看数据的原始视图。其次,不要告诉我们您“看到了异常”而不告诉我们究竟是什么异常。第三,可以使用VS或者json2csharp.com之类的工具将json翻译成C#类。
-
当我使用 JsonConvert.DeserializeObject
(body);我在“body”中看到了数据,当跳到下一行时 exchange = exchangeBody; -> 调试器跳过这一行并转到异常。我用异常消息更新问题。