API calls using HttpClient and deserializing JSON in C#

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:

API Call

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.

JSON to C#

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).

Also, as a rule of thumb, every 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:

And that’s pretty much it!

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:

//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

  • http://hananonymoz.wordpress.com hanxzalah

    Thank very much my lifesaver ! ^_^

  • http://hasyemiraws.wordpress.com hasyemiraws

    Hi Lilian nice tutorial’s, btw i’ve a question, maybe you can give a help.
    How if when i get data from the web services, i want to store or make it available to another page without to call the api over again?

    hope you can help, thank you 🙂

  • http://gravatar.com/privatevendetta1989 Lars

    In VS you can actually go to Edit -> Paste Special… -> Paste JSON As Classes to paste your copied JSON directly into VS

    • http://liliankasem.com Lilian Kasem

      Today I learnt something new, thanks!