我已经构建了一个检索示例文件的服务。
return await _httpClient.GetFromJsonAsync<BitcoinDetails>("https://localhost:44356/sample-data/jsonresult.json");
示例
"id": 1,
"name": "Bitcoin",
"symbol": "BTC",
"slug": "bitcoin",
"num_market_pairs": 9550,
"date_added": "2013-04-28T00:00:00.000Z",
"tags": [
"mineable",
"pow",
"sha-256",
"store-of-value",
"state-channels"
],
"max_supply": 21000000, -- or null if not set
"circulating_supply": 18555956,
"total_supply": 18555956,
"platform": null,
"cmc_rank": 1,
"last_updated": "2020-11-27T21:22:02.000Z",
"quote": {
"USD": {
"price": 17069.598651577406,
"volume_24h": 38571181876.87967,
"percent_change_1h": 1.46329039,
"percent_change_24h": 0.92405679,
"percent_change_7d": -8.25816318,
"market_cap": 316742721516.32965,
"last_updated": "2020-11-27T21:22:02.000Z"
}
}
}
现在我有一个类,它具有以下属性
public class Datum
{
public int id { get; set; }
public string name { get; set; }
public string symbol { get; set; }
public string slug { get; set; }
public int num_market_pairs { get; set; }
public DateTime date_added { get; set; }
public List<string> tags { get; set; }
public long? max_supply { get; set; }
public double circulating_supply { get; set; }
public double total_supply { get; set; }
public Platform platform { get; set; }
public int cmc_rank { get; set; }
public DateTime last_updated { get; set; }
public Quote quote { get; set; }
}
请记住,还有更多的记录,我得到了以下错误
Unhandled exception rendering component: The JSON value could not be converted to System.Nullable`1[System.Int64]. Path: $.data[80].max_supply |
使dto可以为null,然后尝试如下:
var response = client.GetAsync(apiUrl);
if (response.Result.IsSuccessStatusCode)
{
var data = response.Result.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<Datum>(data.Result);
return result;
}
我最终使用了一个代理调用,但这段代码确实有效:
var response = await _httpClient.GetAsync("https://localhost:5001/proxy");
if (response.IsSuccessStatusCode)
{
var data = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<BitcoinDetails>(data);
return result;
}
else
{
throw new Exception("Failed to get data");
}
并将其添加到类属性中
[JsonProperty(NullValueHandling=NullValueHandler.Ignore(]