Introduction

We'll simply discuss how to integrate JSON APIs in our UWP Applications. JSON stands for JavaScript Object Notation and is a famous light-weight format for data interchange. It is being highly used in applications nowadays.

JSON stores data in a Key-Value format. For example:

var Person = {"name": "Hussain", "age": 22};

Here "name" & "age" are keys while their values are "Hussain" & "22" respectively. Hope you've got the idea of what JSON is. You can read more about it here.

Before moving on, weI'll assume that you've installed the latest version of Visual Studio and have basic knowledge of UWP Application Development.

Steps

Install Newtonsoft.Json


After creating a new project, the first thing you need to do is install "Newtonsoft.Json" package from your NuGet Package Manager.



Creating JSON Classes


We are using here a free weather API offered by openweathermap.org. When we open my API in a browser, we get to see this stuff which is in JSON format.



Now follow the following steps carefully:


Lastly, change the weather array to a list in your RootObject class (newly pasted JSON class).

public Weather[] weather {get; set;} //old
 
public List<Weather> weather {get; set;} //new

Parsing JSON


Here we'll use the NuGet package that we installed in our first step. But before moving onto that, let's make a simple text block with which we'nt-weight:bold;">get; set;} //old
 
public List<Weather> weather {get; setMainPage.xaml file.

<TextBlock FontSize="50" Margin="20", x:Name="temperature"/>

Now go to MainPage.xaml.cs file and paste following function there. You may have to add few namespaces after that. You can do that by simply right clicking on the underlined code.

async void getTemperature() {
string url = "http://api.openweathermap.org/data/2.5/weather/?q=Islamabad,pk&APPID=853dbcea2a5b4eb495d21a3cef29d1af";
 
HttpClient client = new HttpClient();
 
string response = await client.GetStringAsync(url);
 
var data = JsonConvert.DeserializeObject<RootObject>(response);
 
temperature.Text = data.main.temp.ToString()+" 'F";
}

Now, just call this function from your main method and you're good to go. On running the app, you'll get to see the temperature in Fahrenheit. If you want to add more stuff, focus on the last line of this method. As we bind data.main.temp to the text block, you can similarly add pressure(data.main.pressure), humidity(data.main.pressure), etc. in your app.

Conclusion

We've created a very simple weather app by consuming a JSON API. This is a very easy approach and you can try this out many other freely available APIs. You can find some useful APIs here.

Have any confusion or suggestion? Please let us know in comments.