0

I am getting the response in the network tab of developer tools, so that means the call is working fine but my variable for some reason is null in the debugger. I get the following error in the console. "Unhandled exception rendering component: Object reference not set to an instance of an object." Following is the code.

    protected override async Task OnInitializedAsync()
    { 
       Http.DefaultRequestHeaders.Add("some-header-here", "some-value-here");
     // var resp = await Http.GetFromJsonAsync<TeacherLocations>("api-url-here", new JsonSerializerOptions{ PropertyNameCaseInsensitive = true });
       var resp = await Http.GetFromJsonAsync<TeacherLocations>("api-url-here");
       var allLocations = resp.TeacherLocationsList.ToArray();
    }

The model TeachersLocations.

    using Newtonsoft.Json;
    
    namespace Teachers.Shared.Models
    {
        public class TeacherLocations
        {
            [JsonProperty("teacher-locations")]
            public List<City> TeacherLocationsList { get; set; }
        }
    }

City model

namespace Teachers.Shared.Models 
{
    public class City
    {
      public int? _id { get; set; }
      public string? region { get; set; }
      public string? name { get; set; }
    }
}

What can be the problem? I put the breakpoint at resp and it always shows me null.

Ravy
  • 3,599
  • 3
  • 11
  • 14
  • 1
    HttpClient.GetFromJsonAsync is not using Newtonsoft.Json but System.Net.Http.Json which in reality is System.Text.Json. Perhaps this would help? --> https://learn.microsoft.com/en-us/aspnet/core/blazor/call-web-api?view=aspnetcore-6.0&pivots=webassembly> I remember there is a default property that needs to be changed so that certain Newtosoft.Json content can be deserialized by System.Text.Json. I'll try to find it. – Shuryno Apr 21 '22 at 20:01
  • This is the property I had to change, PropertyNameCaseInsensitive = true, it is explained here. https://stackoverflow.com/questions/66123549/jsonserializer-deserializeasynct-not-deserializing/66124300#66124300 Perhaps this will solve your issue. – Shuryno Apr 21 '22 at 20:12
  • @Shuryno: I tried your suggestion. I have edited my question with your suggestion as a comment. Is it the correct implementation? – Ravy Apr 21 '22 at 20:46

0 Answers0