I want to deserialize JSON objects by using GetFromJsonAsync
in C#. Easily, values are extracted from JSON, but the problem is sub object values are not being extracted.
For testing, I'm using Open Meteo API. (example API link: https://api.open-meteo.com/v1/forecast?latitude=38.48&longitude=27.24¤t_weather=true)
With my code I get, latitude, longitude, etc. (first part).
But, I can't get temperature, windspeed, etc at current_weather
sub structure.
Sample JSON values:
{
"latitude": 38.4375,
"longitude": 27.25,
"generationtime_ms": 0.21195411682128906,
"utc_offset_seconds": 0,
"timezone": "GMT",
"timezone_abbreviation": "GMT",
"elevation": 137,
"current_weather": {
"temperature": 12.3,
"windspeed": 6.4,
"winddirection": 137,
"weathercode": 3,
"time": "2023-02-26T06:00"
}
}
Latitude
and Longitude
are OK, but the Temperature
always returns zero.
Do you have any idea?
My code is as follows:
using System.Net.Http.Json;
using System.Runtime.ConstrainedExecution;
namespace HttpClientExtensionMethods
{
public class City
{
public float Latitude { get; set; }
public float Longitude { get; set; }
public float Temperature { get; set; }
}
public class Program
{
public static async Task Main()
{
using HttpClient client = new()
{
BaseAddress = new Uri("https://api.open-meteo.com/v1/forecast?latitude=52.52&longitude=13.41¤t_weather=true")
};
// Get Json Weather information.
City? city = await client.GetFromJsonAsync<City>("");
Console.WriteLine($"Latitude: {city?.Latitude}");
Console.WriteLine($"Longitude: {city?.Longitude}");
Console.WriteLine($"Temperature: {city?.Temperature}");
}
}
}
I have tried creating an additional public class for current_weather
, but with no success. I want to reach sub-values under the current_weather
structure.