Nullreferenceexception: Object Reference not set to an instance of an Object. How to resolve?

Asked

Viewed 209 times

0

I am developing an application that consumes data from an API and shows to users, but I am facing an exception:

NullReferenceException: Object reference not set to an instance of an object.

inserir a descrição da imagem aqui

How do I fix it?

Model class:

using System;
using Newtonsoft.Json;

namespace InfoCovid.Models
{
  public class Rootobject
  {
    [JsonProperty("data")]
    public Datum[] Data { get; set; }
  }

  public class Country
  {
    [JsonProperty("data")]
    public Datum Datum { get; set; }
  }

  public class Datum
  {
    [JsonProperty("country")]
    public string Country { get; set; }

    [JsonProperty("cases")]
    public int Cases { get; set; }

    [JsonProperty("confirmed")]
    public int Confirmed { get; set; }

    [JsonProperty("deaths")]
    public int Deaths { get; set; }

    [JsonProperty("recovered")]
    public int Recovered { get; set; }

    [JsonProperty("updated_at")]
    public DateTime UpdatedAt { get; set; }
  }
}

Class PageModel (the one who requests the API):

public Datum[] Data { get; private set; }
public IMemoryCache MemoryCache { get; private set; }

    public async Task OnGetAsync()
    {
      try
      {
        string key_data = "data_key";
        if (!MemoryCache.TryGetValue<Datum[]>(key_data, out Datum[] values))
        {
          var create = RestService
              .For<IGetRootobject>
              ("https://covid19-brazil-api.now.sh/api/report/v1/countries");
          var result = await create.GetAsync();
          Data = result.Data;
          MemoryCache.Set(key_data, Data, System.TimeSpan.FromMinutes(30));
        }
        else
        {
          Data = values;
        }
      }
      catch (Exception e)
      {
        _logger.LogInformation("Erro na requisição http: " + e.Message);
      }
    }

Page Razor:

@page
@model CitiesModel
@{
  ViewData["Title"] = "InfoCovid";
}

<h3>Países</h3>

<div class="card-group">
  @foreach (var item in Model.Data)
  {
    <div class="col-xxl-3 col-lg-3">
      <div class="card mb-4" style="background-color: #2E3140;">
        <div class="card-body">
          <div class="d-flex justify-content-between">
            <div class="mr-3">
              <div class="text-white">@item.Country</div>
              <div class="text-lg text-white font-bold">@item.Deaths</div>
            </div>
          </div>
        </div>
        <div class="card-footer d-flex justify-content-between">
          <a class="small text-white stretched-link" href="#">View Report</a>
        </div>
      </div>
    </div>
  }
</div>
  • Where are you sending the model to View??? debugged your code? The model is irrelevant to the question... Show your controller or Behind page code

  • Learn IGetRootobject

  • I was able to solve the problem. The error was in the model class. I was using property that differed from the return of the api.

  • I edit the post showing the solution?

  • you post the answer, but if it’s what I’m imagining it’s a "silly" mistake right?

1 answer

0

I managed to sort it out like this:

Example of the return of the api:

inserir a descrição da imagem aqui

My class Igetrootobject had as class model for deserialization:

public class Datum
{
  [JsonProperty("uid")]
  public int Uid { get; set; }

  [JsonProperty("uf")]
  public string Uf { get; set; }

  [JsonProperty("state")]
  public string StateName { get; set; }

  [JsonProperty("cases")]
  public int Cases { get; set; }

  [JsonProperty("deaths")]
  public int Deaths { get; set; }

  [JsonProperty("suspects")]
  public int Suspects { get; set; }

  [JsonProperty("refuses")]
  public int Refuses { get; set; }

  [JsonProperty("datetime")]
  public DateTime Datetime { get; set; }
}

That is, there was an incompatibility between the properties. Therefore, the correct model class is:

public class Data
{
  [JsonProperty("country")]
  public string Country { get; set; }

  [JsonProperty("cases")]
  public int Cases { get; set; }

  [JsonProperty("confirmed")]
  public int Confirmed { get; set; }

  [JsonProperty("deaths")]
  public int Deaths { get; set; }

  [JsonProperty("recovered")]
  public int Recovered { get; set; }

  [JsonProperty("updated_at")]
  public DateTime UpdatedAt { get; set; }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.