Introduction
We'll simply discuss how to integrate JSON APIs in our UWP applications. JSON stands for JavaScript Object Notation, and is famous light-weight format of data interchange. It is being highly used in applications now-a-days.
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. I hope you've got the idea of what JSON is.
Before moving on, I'll assume that you've installed latest version of Visual Studio and have the basic knowledge of UWP Application Development.
Install Newtonsoft.Json After creating a new project, first thing you need to do is install "Newtonsoft.Json" package from your NuGet Package Manager.
Creating JSON Classes I'm using here a free weather API offered by openweathermap.org. When I open my API in a browser, I get to see this stuff which is in JSON format.
Now, follow these steps carefully.
- Copy your JSON data from browser.
- Go to your Visual Studio project and create a new class "weatherData".
- Remove existing class from your weatherData.cs file.
- Click on Edit > Paste Special > Paste JSON As Classes. This will convert and paste your JSON data as C# classes.
Lastly, change the weather array to a list in your RootObject class (newly pasted JSON class).
- public Weather[] weather {get; set;}
- public List<Weather> weather {get; set;}
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 textblock with which we'll bind some data to display our weather. Put the following code in your MainPage.xaml file.
- <TextBlock FontSize="50" Margin="20", x:Name="temperature"/>
Now, go to MainPage.xaml.cs file and paste the 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 last line of this method. As I binded data.main.temp to my textblock, 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 very easy approach. You can try this out with many other freely available APIs.
Have any confusion or suggestion? Please let me know in comments.