Getting JSON Data From a RESTful API Using JAVA

Gayanga Kuruppu
The Startup
Published in
2 min readAug 2, 2020

Introduction

I like Java. It’s my go to object oriented programming language. It’s easy to use and it gets the job done. Recently, I had to implement an application that gets data from a REST API using Java and oh my god! I started hating Java.

Having previously worked with technologies such as “ReactJS”, getting JSON (JavaScript Object Notation) data from a RESTful API is just an “axios” call away. JavaScript makes it so easy for me to work with JSON data. Java on the other hand was a mess, and there was no proper material online that I could refer to. So I decided to help anyone who’s struggling to do this in Java.

Before we begin make sure you have downloaded and installed the JSON Simple Java library (https://github.com/fangyidong/json-simple). For this article I’ll be using the REST API for Covid-19 (https://api.covid19api.com/)

This is how our JSON data will look,

Getting things done

First let’s set the URL object and type cast it into an HttpURLConnection object so that we can set request types and get response codes back. Since we’re only going to get data from the endpoint, let’s set the request method to “GET” and connect. Now we’ll be able to get a response code.

Make sure everything is inside a try and catch block :)

Now that we have a response code, let’s check if it’s successful and if so do the rest of the work.

If the response code is not 200 (Successful) we throw a new exception, otherwise we use a scanner to go through the URL stream and write all the data we get into a string.

Then using the JSON Simple library we parse that string into a JSON object. Then we can get the object (or array) we want from that object using its key. Here I took the “Global” object containing all the global statistics and displayed the total number of recovered individuals.

If you want to access an array we simply cast the object we want to a JSONArray and within a for loop try to find the specific object we want from inside the array.

Here you can see the code to get the total number of recovered individuals from “Albania”

The code

Below you can find the code we used in its entirety,

I hope this article helped anyone who was struggling with this problem. If I forgot to cover something or if something was unclear please let me know :)

--

--