Loading, please wait...

A to Z Full Forms and Acronyms

What next after making the JSON serialization in UWP App

This article briefs you about using the JSON format to interact with the incoming data and lot more this time

Pre-requisite Knowledge

Before we start with the understanding of this app, we should know-

  1. Understanding of UWP
  2. Hands-On on UWP Application
  3. Layout Panels
  4. Using APIs with C# in UWP (IMP)
  5. How to work with json in UWP C#

In this article we’ll move forward on the application build in the previous article, the source code for the same can be found here (on GitHub)

Now let’s go see the code:

  1. Let’s get started with the creation of this Application.

  2. Same old steps, Open Visual Studio (I’ll use VS 2019, Community Edition for this demo- It’s free)

  3. After opening Visual Studio, click on Create a New Project or (open the exisitng on if you've cloned the source code from above)
  4. On the next screen, Search for “UWP” in the top given search bar and then select “Blank App (Universal Windows)”, then simply click on Next
  5. Give your project a name, then click on Next
  6. Here we can select the versions accordingly, but for this demo, I’m keeping it untouched.
  7. After the solution has been created, right-click on the project and then select “Add package”
  8. Now search for Newtonsoft.json and then select it from search result, then finally click on install button on the right.
  9. The package can be seen inside the references folder from the solution explorer at the right side.
  10. After Cloning the API Demo 2 Project navigate to the MainPage.xaml file and replace the stack layout code with the below code
    <Page
        x:Class="apiDemoUWP3.MainPage"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="using:apiDemoUWP3"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    
        <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
            <TextBox IsEnabled="False" Text="Check latitude and longitude" />
            <TextBox x:Name="cityName" Text="Delhi" />
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="Auto" />
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto" />
                    <ColumnDefinition Width="*" />
                </Grid.ColumnDefinitions>
                <Button Content="Get Location ID" HorizontalAlignment="Center" Click="getID_CLick" Grid.Column="0" Grid.Row="0"/>
                <Button Content="Show Weather" HorizontalAlignment="Center" Click="showWeather_Click" Grid.Column="1" Grid.Row="0"/>
            </Grid>
                <TextBox x:Name="weatherForecast" Text="Coordinates Here" TextWrapping="Wrap"
                         HorizontalAlignment="Center" Height="200" Width="300" Grid.Row="1"/>
        </StackPanel>
    </Page>​

  11. After the front end code is ready, now before diving to the backend code, let’s have a watch on the location API, for this we’ll use an application named “Postman” (a robust application for API testing and lot more).

    WebBrowser:





    PostMan


  12. Now lets head to edit the class Weather.cs file to parse the JSON responses.
    using Newtonsoft.Json;
    using System;
    using System.Collections.Generic;
    
    namespace apiDemoUWP3
    {
        internal class Weather
        {
            [JsonProperty("consolidated_weather")]
            public List<ConsolidatedWeather> ConsolidatedWeather { get; set; }
    
            [JsonProperty("time")]
            public DateTimeOffset Time { get; set; }
    
            [JsonProperty("sun_rise")]
            public DateTimeOffset SunRise { get; set; }
    
            [JsonProperty("sun_set")]
            public DateTimeOffset SunSet { get; set; }
    
            [JsonProperty("timezone_name")]
            public string TimezoneName { get; set; }
    
            [JsonProperty("parent")]
            public Parent Parent { get; set; }
    
            [JsonProperty("sources")]
            public List<Source> Sources { get; set; }
    
            [JsonProperty("title")]
            public string Title { get; set; }
    
            [JsonProperty("location_type")]
            public string LocationType { get; set; }
    
            [JsonProperty("woeid")]
            public long Woeid { get; set; }
    
            [JsonProperty("latt_long")]
            public string LattLong { get; set; }
    
            [JsonProperty("timezone")]
            public string Timezone { get; set; }
        }
    
        public partial class ConsolidatedWeather
        {
            [JsonProperty("id")]
            public long Id { get; set; }
    
            [JsonProperty("weather_state_name")]
            public string WeatherStateName { get; set; }
    
            [JsonProperty("weather_state_abbr")]
            public string WeatherStateAbbr { get; set; }
    
            [JsonProperty("wind_direction_compass")]
            public string WindDirectionCompass { get; set; }
    
            [JsonProperty("created")]
            public DateTimeOffset Created { get; set; }
    
            [JsonProperty("applicable_date")]
            public DateTimeOffset ApplicableDate { get; set; }
    
            [JsonProperty("min_temp")]
            public double MinTemp { get; set; }
    
            [JsonProperty("max_temp")]
            public double MaxTemp { get; set; }
    
            [JsonProperty("the_temp")]
            public double TheTemp { get; set; }
    
            [JsonProperty("wind_speed")]
            public double WindSpeed { get; set; }
    
            [JsonProperty("wind_direction")]
            public double WindDirection { get; set; }
    
            [JsonProperty("air_pressure")]
            public double AirPressure { get; set; }
    
            [JsonProperty("humidity")]
            public long Humidity { get; set; }
    
            [JsonProperty("visibility")]
            public double Visibility { get; set; }
    
            [JsonProperty("predictability")]
            public long Predictability { get; set; }
        }
    
        public partial class Parent
        {
            [JsonProperty("title")]
            public string Title { get; set; }
    
            [JsonProperty("location_type")]
            public string LocationType { get; set; }
    
            [JsonProperty("woeid")]
            public long Woeid { get; set; }
    
            [JsonProperty("latt_long")]
            public string LattLong { get; set; }
        }
    
        public partial class Source
        {
            [JsonProperty("title")]
            public string Title { get; set; }
    
            [JsonProperty("slug")]
            public string Slug { get; set; }
    
            [JsonProperty("url")]
            public Uri Url { get; set; }
    
            [JsonProperty("crawl_rate")]
            public long CrawlRate { get; set; }
        }
        
        internal class Location
        {
            public string title;
            public string location_type;
            public string woeid;
            public string latt_long;
        }
    }
    ​

  13. For the Backend Code, edit the MainPage.xaml.cs file as below:
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;
    using System.Net.Http;
    using System;
    using Newtonsoft.Json;
    using System.Collections.Generic;
    
    // The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
    
    namespace apiDemoUWP3
    {
        /// <summary>
        /// An empty page that can be used on its own or navigated to within a Frame.
        /// </summary>
        public sealed partial class MainPage : Page
        {
            private string choiceSelected = "";
            private int locationID;
            public MainPage()
            {
                this.InitializeComponent();
            }
            private async void getID_CLick(object sender, RoutedEventArgs e)
            {
                try
                {
                    var client = new HttpClient();
    
                    choiceSelected = cityName.Text.ToLower();
    
                    // Request parameters
                    var url = "https://www.metaweather.com/api/location/search/?query=" + choiceSelected;
    
                    // Asynchronously call the REST API method.
                    var response = await client.GetAsync(url);
    
                    // Asynchronously get the JSON response.
                    string contentString = await response.Content.ReadAsStringAsync();
                    client.Dispose();
    
                    Location location = new Location();
    
                    weatherForecast.Text = "";
                    List<Location> locationObj = JsonConvert.DeserializeObject
                        <List<Location>>(contentString);
                    weatherForecast.Text = String.Format("{0}- {1}", locationObj[0].title, locationObj[0].woeid);
                    locationID = Int32.Parse(locationObj[0].woeid);
                }
                catch (Exception exObj)
                {
                    weatherForecast.Text += "  Error Occured-- " + exObj.Message;
                }
            }
            private async void showWeather_Click(object sender, RoutedEventArgs e)
            {
                try
                {
                    var client = new HttpClient();
    
                    choiceSelected = cityName.Text.ToLower();
    
                    // Request parameters
                    string url = "https://www.metaweather.com/api/location/" + locationID.ToString();
    
                    // Asynchronously call the REST API method.
                    var response = await client.GetAsync(url);
    
                    // Asynchronously get the JSON response.
                    string contentString = await response.Content.ReadAsStringAsync();
                    client.Dispose();
    
                    Weather weather = new Weather();
    
                    weatherForecast.Text += "\n";
                    Weather weatherObj = JsonConvert.DeserializeObject
                        <Weather>(contentString);
    
                    var day1Weather = weatherObj.ConsolidatedWeather[0];
                    weatherForecast.Text += "--------------------------";
                    weatherForecast.Text += "Day1 Weather: \n";
                    weatherForecast.Text += "\nWeather State: " + day1Weather.WeatherStateName;
                    weatherForecast.Text += "\nTemprature: " + day1Weather.TheTemp;
                    weatherForecast.Text += "\nAir Pressure: " + day1Weather.AirPressure;
                    weatherForecast.Text += "\nHumidity: " + day1Weather.Humidity;
    
                }
                catch (Exception exObj)
                {
                    weatherForecast.Text += "  Error Occured-- " + exObj.Message;
                }
            }
        }
    }
    ​

  14. And this completes our application: Now lets run it! (Press ‘F5’ key)



Hope you like this article, stay tuned, I have a lot to share in the very near future

Conclusion - In this article, we have learned about:

    1. Deserializing a real Weather Data from a Dynamic JSON Response from the Weather API.
A to Z Full Forms and Acronyms

Related Article