question

JassimAlRahma-9056 avatar image
0 Votes"
JassimAlRahma-9056 asked LeonLu-MSFT edited

Get forecast from weatherapi.com

Hi,

I have below code to consume the forecast weather from weatherapi.com:

 async void GetForecast()
 {
     var client = new HttpClient();
    
     string url = string.Format("{0}/current.json?key={1}&q={2},{3}", App.WeatherURL, App.WeatherAPI, App.Latitude, App.Longitude);
    
     client.BaseAddress = new Uri(url);
        
     var response = await client.GetAsync(url);
     var result = await response.Content.ReadAsStringAsync();
    
     CurrentWeather.Root data = JsonSerializer.Deserialize<CurrentWeather.Root>(result);
    
     ListViewForecast.ItemsSource = data;
 }



and I am getting the correct data from the JSON as you can see in below image:

199970-screen-shot-2022-05-08-at-92036-pm.png

but the problem is I am not able to show the data in my XAML. I tried:

 Text="{Binding forecast.forecastday.hour.temp_c}"

Here is my complete Class:

using System;
using System.Collections.Generic;

namespace MyWeatherApp
{
    class ForecastWeather
    {
        // Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
        public class Astro
        {
            public string sunrise { get; set; }
            public string sunset { get; set; }
            public string moonrise { get; set; }
            public string moonset { get; set; }
            public string moon_phase { get; set; }
            public string moon_illumination { get; set; }
        }

        public class Condition
        {
            public string text { get; set; }
            public string icon { get; set; }
            public int code { get; set; }
        }

        public class Current
        {
            public int last_updated_epoch { get; set; }
            public string last_updated { get; set; }
            public double temp_c { get; set; }
            public double temp_f { get; set; }
            public int is_day { get; set; }
            public Condition condition { get; set; }
            public double wind_mph { get; set; }
            public double wind_kph { get; set; }
            public int wind_degree { get; set; }
            public string wind_dir { get; set; }
            public double pressure_mb { get; set; }
            public double pressure_in { get; set; }
            public double precip_mm { get; set; }
            public double precip_in { get; set; }
            public int humidity { get; set; }
            public int cloud { get; set; }
            public double feelslike_c { get; set; }
            public double feelslike_f { get; set; }
            public double vis_km { get; set; }
            public double vis_miles { get; set; }
            public double uv { get; set; }
            public double gust_mph { get; set; }
            public double gust_kph { get; set; }
        }

        public class Day
        {
            public double maxtemp_c { get; set; }
            public double maxtemp_f { get; set; }
            public double mintemp_c { get; set; }
            public double mintemp_f { get; set; }
            public double avgtemp_c { get; set; }
            public double avgtemp_f { get; set; }
            public double maxwind_mph { get; set; }
            public double maxwind_kph { get; set; }
            public double totalprecip_mm { get; set; }
            public double totalprecip_in { get; set; }
            public double avgvis_km { get; set; }
            public double avgvis_miles { get; set; }
            public double avghumidity { get; set; }
            public int daily_will_it_rain { get; set; }
            public int daily_chance_of_rain { get; set; }
            public int daily_will_it_snow { get; set; }
            public int daily_chance_of_snow { get; set; }
            public Condition condition { get; set; }
            public double uv { get; set; }
        }

        public class Forecast
        {
            public List<Forecastday> forecastday { get; set; }
        }

        public class Forecastday
        {
            public string date { get; set; }
            public int date_epoch { get; set; }
            public Day day { get; set; }
            public Astro astro { get; set; }
            public List<Hour> hour { get; set; }
        }

        public class Hour
        {
            public int time_epoch { get; set; }
            public string time { get; set; }
            public double temp_c { get; set; }
            public double temp_f { get; set; }
            public int is_day { get; set; }
            public Condition condition { get; set; }
            public double wind_mph { get; set; }
            public double wind_kph { get; set; }
            public int wind_degree { get; set; }
            public string wind_dir { get; set; }
            public double pressure_mb { get; set; }
            public double pressure_in { get; set; }
            public double precip_mm { get; set; }
            public double precip_in { get; set; }
            public int humidity { get; set; }
            public int cloud { get; set; }
            public double feelslike_c { get; set; }
            public double feelslike_f { get; set; }
            public double windchill_c { get; set; }
            public double windchill_f { get; set; }
            public double heatindex_c { get; set; }
            public double heatindex_f { get; set; }
            public double dewpoint_c { get; set; }
            public double dewpoint_f { get; set; }
            public int will_it_rain { get; set; }
            public int chance_of_rain { get; set; }
            public int will_it_snow { get; set; }
            public int chance_of_snow { get; set; }
            public double vis_km { get; set; }
            public double vis_miles { get; set; }
            public double gust_mph { get; set; }
            public double gust_kph { get; set; }
            public double uv { get; set; }
        }

        public class Location
        {
            public string name { get; set; }
            public string region { get; set; }
            public string country { get; set; }
            public double lat { get; set; }
            public double lon { get; set; }
            public string tz_id { get; set; }
            public int localtime_epoch { get; set; }
            public string localtime { get; set; }
        }

        public class Root
        {
            public Location location { get; set; }
            public Current current { get; set; }
            public Forecast forecast { get; set; }
        }
    }
}


dotnet-csharpdotnet-xamarin
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

LeonLu-MSFT avatar image
0 Votes"
LeonLu-MSFT answered LeonLu-MSFT edited

Hello,​

Firstly, we cannot use Text="{Binding forecast.forecastday.hour.temp_c}" to get temp_c directly. Because forecastday and hour are List<>.

I use free Api from weatherapi to get forecast. When we deserialize Json to get ForecastWeather.Root object, we need to ForecastWeather.Forecast object by data.forecast, then get List<ForecastWeather.Forecastday> by forecast.forecastday. Now we get a List, I make a test to get the first record, So I use forecastdays[0] to get List<Hour>, it is a List as well, I get the first record for testing by forecastdays[0].hour[0], then we can get the temp_c property like following code.


async void GetForecast()
        {
            var client = new HttpClient();

            string url = "https://api.weatherapi.com/v1/forecast.json?key=8c1e055xxxxxxxxxxxxxxxxxx905&q=London&days=7&aqi=yes&alerts=no";
            //string url = string.Format("{0}/current.json?key={1}&q={2},{3}", App.WeatherURL, App.WeatherAPI, App.Latitude, App.Longitude);
            client.BaseAddress = new Uri(url);

            var response = await client.GetAsync(url);
            string result = await response.Content.ReadAsStringAsync();
            ForecastWeather.Root data =   JsonSerializer.Deserialize<ForecastWeather.Root>(result);

            ForecastWeather.Forecast forecast = data.forecast;
            List<ForecastWeather.Forecastday> forecastdays= forecast.forecastday;
            double s=forecastdays[0].hour[0].temp_c;
          
        }



Best Regards,

Leon Lu



If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


· 6
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

but how can I get the Binding inside the XAML? I tried below but did not work:

 <Label Margin="0,5,0,5" Text="{Binding hour.temp_c}" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" HorizontalTextAlignment="Start" FontSize="15" LineBreakMode="WordWrap" />



This is the codebehind as per your help:

 HttpClient forecast_client = new HttpClient();
    
 string forecast_url = string.Format("https://api.weatherapi.com/v1/forecast.json?key={1}&q={2},{3}", App.WeatherURL, App.WeatherAPI, App.Latitude, App.Longitude);
    
 forecast_client.BaseAddress = new Uri(forecast_url);
    
 var forecast_response = await forecast_client.GetAsync(forecast_url);
 var forecast_result = await forecast_response.Content.ReadAsStringAsync();
    
 ForecastWeather.Root forecast_data = JsonSerializer.Deserialize<ForecastWeather.Root>(forecast_result);
 ForecastWeather.Forecast forecast = forecast_data.forecast;
 List<ForecastWeather.Forecastday> forecastdays = forecast.forecastday;
    
 ListViewForecast.ItemsSource = forecastdays;





0 Votes 0 ·
LeonLu-MSFT avatar image LeonLu-MSFT JassimAlRahma-9056 ·

Change your binding Text like following code.

<Label Text="{Binding hour[0].temp_c}"></Label>
0 Votes 0 ·

but this will get the first hour only and I want o list all hours.\

I also tried below but did not work:

C#:

 HttpClient forecast_client = new HttpClient();
    
 forecast_client.Timeout = TimeSpan.FromSeconds(App.HttpClient_TimeOut);
 string forecast_url = string.Format("https://api.weatherapi.com/v1/forecast.json?key={1}&q={2},{3}", App.WeatherURL, App.WeatherAPI, App.Latitude, App.Longitude);
    
 forecast_client.BaseAddress = new Uri(forecast_url);
    
 var forecast_response = await forecast_client.GetAsync(forecast_url);
 var forecast_result = await forecast_response.Content.ReadAsStringAsync();
    
 ForecastWeather.Root forecast_data = JsonSerializer.Deserialize<ForecastWeather.Root>(forecast_result);
 ForecastWeather.Forecast forecast = forecast_data.forecast;
 // List<ForecastWeather.Forecastday> forecastdays = forecast.forecastday;
    
 ListViewForecast.ItemsSource = forecast;


XAML:

 <Label Text="{Binding forecastday[0].hour.temp_c}" />



0 Votes 0 ·
Show more comments