Home > Net >  Using an API is giving error "An object reference is required for the nonstatic field, method,
Using an API is giving error "An object reference is required for the nonstatic field, method,

Time:06-06

As a beginner, I still don't understand completely what I'm doing. I'm trying to add a weather API to a webpage but when I try to call the class on the view, it doesn't work and I get an error "An object reference is required for the non-static field, method, or property 'WeatherApi.Current.Temperature'"

Model

using Newtonsoft.Json;

namespace Exercice.Models
{
    public class WeatherApi
    {
        //Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
        public class Current
        {
            [JsonProperty("observation_time")]
            public string ObservationTime { get; set; }

            [JsonProperty("temperature")]
            public int Temperature { get; set; }

            [JsonProperty("weather_code")]
            public int WeatherCode { get; set; }

            [JsonProperty("weather_icons")]
            public List<string> WeatherIcons { get; set; }

            [JsonProperty("weather_descriptions")]
            public List<string> WeatherDescriptions { get; set; }

            [JsonProperty("wind_speed")]
            public int WindSpeed { get; set; }

            [JsonProperty("wind_degree")]
            public int WindDegree { get; set; }

            [JsonProperty("wind_dir")]
            public string WindDir { get; set; }

            [JsonProperty("pressure")]
            public int Pressure { get; set; }

            [JsonProperty("precip")]
            public int Precip { get; set; }

            [JsonProperty("humidity")]
            public int Humidity { get; set; }

            [JsonProperty("cloudcover")]
            public int Cloudcover { get; set; }

            [JsonProperty("feelslike")]
            public int Feelslike { get; set; }

            [JsonProperty("uv_index")]
            public int UvIndex { get; set; }

            [JsonProperty("visibility")]
            public int Visibility { get; set; }

            [JsonProperty("is_day")]
            public string IsDay { get; set; }
        }

        public class Location
        {
            [JsonProperty("name")]
            public string Name { get; set; }

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

            [JsonProperty("region")]
            public string Region { get; set; }

            [JsonProperty("lat")]
            public string Lat { get; set; }

            [JsonProperty("lon")]
            public string Lon { get; set; }

            [JsonProperty("timezone_id")]
            public string TimezoneId { get; set; }

            [JsonProperty("localtime")]
            public string Localtime { get; set; }

            [JsonProperty("localtime_epoch")]
            public int LocaltimeEpoch { get; set; }

            [JsonProperty("utc_offset")]
            public string UtcOffset { get; set; }
        }

        public class Request
        {
            [JsonProperty("type")]
            public string Type { get; set; }

            [JsonProperty("query")]
            public string Query { get; set; }

            [JsonProperty("language")]
            public string Language { get; set; }

            [JsonProperty("unit")]
            public string Unit { get; set; }
        }

        public class Root
        {
            [JsonProperty("request")]
            public Request Request { get; set; }

            [JsonProperty("location")]
            public Location Location { get; set; }

            [JsonProperty("current")]
            public Current Current { get; set; }
        }
    }
}

Controller

public async Task<IActionResult> Weather()
        {
            string baseAddress = "http://api.weatherstack.com/";
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri(baseAddress);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new
            MediaTypeWithQualityHeaderValue("application/json"));
            string path = "current?access_key=<MYACCESSKEY>&query=Madrid";
            HttpResponseMessage response = client.GetAsync(path).Result;
            string myJsonResponse = await response.Content.ReadAsStringAsync();
            WeatherApiResponse apiResponse =
            JsonConvert.DeserializeObject<WeatherApiResponse>(myJsonResponse);

            return View(apiResponse);
        }

View

@model WeatherApi

<p>Temperature @Model.Current.Temperature&deg;</p>

CodePudding user response:

There is something wrong in your WeatherApi definition. Instead of putting class definitions inside, let define model like that:

public class WeatherApi 
{
    public Current Current { get; set; }
    // rest of properties...
}

Beside of that if I correctly remember, you don't have to define attributes for names in JSON, unless you want name property differently than in code.

Also let use @model instead of @Model, because you use small first letter in model definition:

<p>Temperature @model.Current.Temperature&deg;</p>

CodePudding user response:

This happens when you try to reference a property or function on an object when it's null or before it's been initialized to anything.

Basically, you're going to want to look for "." and then ensure that everything BEFORE the "." is null.

In this line below, it looks like either Model or Model.Current might be null.

Model.Current.Temperature

You could try to "protect" any such objects with a null check.

@if (@Model != null && @Model.Current != null)
{
    <p>Temperature @Model.Current.Temperature&deg;</p> 
}

But you really would have to debug thru the C# code and find out what is null and why is it null. It could be a problem with what the API is returning.

  • Related