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

Blazor Json to class conversion failure

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

I have built a service that is retrieving a sample file.

 return await _httpClient.GetFromJsonAsync<BitcoinDetails>("https://localhost:44356/sample-data/jsonresult.json");

Example

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

}

Now I have a class that has the following properties

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

Keeping in mind that there are many more records I am getting the following error

 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

I ended up using a proxy call however this code did work:

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

and added this to the class property

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]