I recently started learning how to develop Universal Windows Platform (UWP) applications and found a simple way of getting JSON formatted data from APIs into a UWP app using C#. I started out by following a tutorial on how to build a weather application, it’s part of a Windows 10 development series and I highly recommend checking it out to help you get started with UWP.

JSON to C#:

There is a great tool that transforms JSON into C# classes (found here). This is really useful as it pretty much does a lot of the work for you.

First make an API call to get the JSON you will be using. I’m going to use the weather map example:

Screen-Shot-2015-10-17-at-12.32.51

Then copy all of the JSON into the JSON to C# class generator, this will give you a set of classes you can use as the data model of your app. You can just copy and paste the classes generated into a C# class, let’s say ‘WeatherProxy’ – this will be where we do all of the HttpClient logic of calling the API and deserializing the JSON returned.

NB: make sure to check through the generated C# classes as they may be generated incorrectly or something might not fit and may cause errors in your code.

Screen-Shot-2015-10-17-at-12.33.12

Setting up the data model:

Once you’ve pasted the C# classes into a class in your UWP application, you will have to add [DataContract] above every class and [DataMember] to every item inside of that class (as shown below). This tells the serializer to treat the class like a class and it’s members as properties. It’s important to do this to every class generated.

You will need the following import: using System.Runtime.Serialization

[DataContract]
    public class Weather
    {
        [DataMember]
        public int id { get; set; }

        [DataMember]
        public string main { get; set; }

        [DataMember]
        public string description { get; set; }

        [DataMember]
        public string icon { get; set; }
    }
Making a call to the API

Now we can use HttpClient to call the API, get the JSON data and deserialize it. You will need to add the ‘Microsoft.Net.Http’ NuGet package and import it into your class (using System.Net.Http).

Eevery time you see the word Async being used i.e. the _http.GetAsync()_ method, you must add _async_ to your method definition and add _await_ before calling the Async method (e.g. http.GetAsync) as seen in the code snippet below.

If you’re new to asynchronous programming, there is a great introduction you can read here: Asynchronous Programming with Async and Await (C# and Visual Basic).

public class WeatherProxy
    {
        public async static Task<RootObject> GetWeather(double lat, double lon)
        {
            var http = new HttpClient();
            var url = String.Format("http://api.openweathermap.org/data/2.5/weather?lat={0}&amp;amp;lon={1}&amp;amp;units=metric", lat, lon);
            var response = await http.GetAsync(url);
            var result = await response.Content.ReadAsStringAsync();
            var serializer = new DataContractJsonSerializer(typeof(RootObject));

            var ms = new MemoryStream(Encoding.UTF8.GetBytes(result));
            var data = (RootObject) serializer.ReadObject(ms);

            return data;
        }
    }
Using the API call results

Now we can just call the GetWeather method to make a call to the weather API, deserialize the JSON data returned into a RootObject, and then use the RootObject to pull the data we want to use.

Here is an example of how we can use the code written above to pull the data we need to display to the user:

Screen-Shot-2015-10-17-at-12.41.20

// Create a RootObject which will contain the results of the GetWeather API call
RootObject myWeather = await WeatherProxy.GetWeather(35, 139);

// Now we can use the RootObject 'myWeather' to get the data we need
TempTextBlock.Text = ((int)myWeather.main.temp).ToString() + "°C";
DescTextBlock.Text = myWeather.weather[0].description;
LocationTextBlock.Text = myWeather.name;

This technique can easily be reused in any other application that make an API call or that uses JSON, or any web service call in general using HttpClient.

I hope you found this useful, I know I will be using the JSON to C# generator as it’s a huge time saver for me!

If you want to have a look at the full code for the weather application, you can find it here on github:

https://github.com/liliankasem/UWP-Weather


Photo by Roozbeh Eslami on Unsplash