Warm tip: This article is reproduced from serverfault.com, please click

c#-Blazor Json到类的转换失败

(c# - Blazor Json to class conversion failure)

发布于 2020-11-27 22:03:51

我已经建立了一个检索示例文件的服务。

 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 | 
Questioner
Jed
Viewed
0
Jed 2020-12-04 01:57:51

我最终使用了代理调用,但是这段代码确实起作用了:

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");
        }

并将其添加到class属性

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]