How to Parse JSON Data From a REST API Using a Simple JSON Library
This quick tutorial will show you how you can use JAVA to leverage JSON data from a REST API and parse it as a JSON object.
Join the DZone community and get the full member experience.
Join For FreeBefore starting, I would like my readers to first understand what a JSON based API is. JSON (JavaScript Object Notation) is a lightweight data interchange format that is now being used as a profound and efficient way of gathering, collecting, or share data among applications and interfaces. JSON provides data to its corresponding calling function in key value pairs, ‘key’ as in the variable and ‘value’ as in the corresponding value for the variable. The data that is parsed from a JSON API is in the form of objects that need to be converted into their respective data formats as acceptable by the system.
I won’t go into much detail describing APIs in this blog post. REST (Representational State Transfer) is an architectural style and is an approach to communications between different modules often used in the development of web services. In this blog, I will describe how you can use JAVA to leverage JSON data from a REST API.
Before starting here is the REST API I am using to parse data into my system JSON-API.
Now what is the use of parsing JSON data from a web service when I can have it in my system already ? The answer to that would be now a days maximum of the client data is available over the web as it is not prone to data loss. More over clients built around JSON API are able to take advantage of its features around efficiently caching responses, sometimes eliminating network requests entirely. So let’s proceed ahead and I would try to explain the process of parsing the data step wise.
Step 1) Pass the desired URL as an object:
URL url = new URL(“The required URL”);
Step 2) Type cast the URL object into a HttpURLConnection object. The benefit of doing this is that we will be able to harness the properties of the HttpURLConnection class to validate features. For example, set the request type or check the status of the response code:
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
Step 3) Set the request type, as in, whether the request to the API is a GET request or a POST request.
conn.setRequestMethod(“GET”);
Step 4) Open a connection stream to the corresponding API.
conn.connect();
Step 5) Get the corresponding response code.
int responsecode = conn.getResponseCode();
Step 6) Now we need to perform a check so that if the response code is not 200, we throw a runtime exception, or otherwise carry on the rest of the procedure. The structure would be like this:
if(responsecode != 200)
throw new RuntimeException(“HttpResponseCode: “ +responsecode);
else
{
Next part of the functionality
}
Step 7) I have used the method scanner to read each line from the API and fetch the data in string format. Now, this part is inside else { } like I mentioned above.
Scanner sc = new Scanner(url.openStream());
while(sc.hasNext())
{
inline+=sc.nextLine();
}
System.out.println(“\nJSON data in string format”);
System.out.println(inline);
sc.close();
The parsed data will something like this:
{
“results”:[
{
“address_components”:[
{
“long_name”:“Chicago”,
“short_name”:“Chicago”,
“types”:[
“locality”,
“political”
]
},
{
“long_name”:“Cook County”,
“short_name”:“Cook County”,
“types”:[
“administrative_area_level_2”,
“political”
]
},
{
“long_name”:“Illinois”,
“short_name”:“IL”,
“types”:[
“administrative_area_level_1”,
“political”
]
},
{
“long_name”:“United States”,
“short_name”:“US”,
“types”:[
“country”,
“political”
]
}
],
“formatted_address”:“Chicago,
IL,
USA”,
“geometry”:{
“bounds”:{
“northeast”:{
“lat”:42.023131,
“lng”:-87.52404399999999
},
“southwest”:{
“lat”:41.6443349,
“lng”:-87.9402669
}
},
“location”:{
“lat”:41.8781136,
“lng”:-87.6297982
},
“location_type”:“APPROXIMATE”,
“viewport”:{
“northeast”:{
“lat”:42.023131,
“lng”:-87.52404399999999
},
“southwest”:{
“lat”:41.6443349,
“lng”:-87.9402669
}
}
},
“place_id”:“ChIJ7cv00DwsDogRAMDACa2m4K8”,
“types”:[
“locality”,
“political”
]
}
],
“status”:“OK”
}
Now you have all the data with you from the API. Somehow, it looks a bit unstructured, and you will definitely need the data categorically and not all the data as a whole. For this, you need to parse this data into a JSON object. In some cases, you need to store the data in JSON array as well.
JAVA by default does not have any inbuilt class or provide any inbuilt class and method to parse and store these data as objects, so for that, you need the class JSONObject (to store the corresponding string data as JSON objects), JSONArray (to hold JSON objects in an array) and JSONParser (to convert string object into JSON objects). For that, you will need a package called SimpleJSON. Download the required jar files and configure its class path in the system.
Step 8) Declare an instance of the JSONParser:
JSONParser parse = new JSONParser();
Step 9) Convert the string objects into JSON objects:
JSONObject jobj = (JSONObject)parse.parse(inline);
If you view the JSON structure, it will be something like this:
{
"results" : [
{
"place_id" : "ChIJ7cv00DwsDogRAMDACa2m4K8",
"types" : [ "locality", "political" ]
} ]
}
I would now like to get the corresponding values under the results array.
Step 10) First, convert the JSON object into JSONArray object like this:
JSONArray jsonarr_1 = (JSONArray) jobj.get(“results”);
Step 11) Once the JSON objects are stored in the array, read the corresponding JSONArray objects, and convert it to JSON objects again so you get the elements within the results array. Here is how you do it:
//Get data for Results array
for(int i=0;i<jsonarr_1.size();i++)
{
//Store the JSON objects in an array
//Get the index of the JSON object and print the values as per the index
JSONObject jsonobj_1 = (JSONObject)jsonarr_1.get(i);
System.out.println(“Elements under results array”);
System.out.println(“\nPlace id: ” +jsonobj_1.get(“place_id”));
System.out.println(“Types: ” +jsonobj_1.get(“types”));
}
Let us dig a bit deeper. Now let us suppose I want the components of “address_components.” Here is the JSON structure:
{
"results" : [
{
"address_components" : [
{
"long_name" : "Chicago",
"short_name" : "Chicago",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Cook County",
"short_name" : "Cook County",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "Illinois",
"short_name" : "IL",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "United States",
"short_name" : "US",
"types" : [ "country", "political" ]
}
]
So how would I get the components under the address_components array? Follow the same step as above
Now we parse the JSON data present in the string format:
//Parse the JSON data present in the string format
JSONParser parse = new JSONParser();
//Type caste the parsed json data in json object
JSONObject jobj = (JSONObject)parse.parse(inline);
//Store the JSON object in JSON array as objects (For level 1 array element i.e Results)
JSONArray jsonarr_1 = (JSONArray) jobj.get(“results”);
//Get data for Results array
for(int i=0;i<jsonarr_1.size();i++)
{
//Store the JSON objects in an array
//Get the index of the JSON object and print the values as per the index
JSONObject jsonobj_1 = (JSONObject)jsonarr_1.get(i);
//Store the JSON object in JSON array as objects (For level 2 array element i.e Address Components)
JSONArray jsonarr_2 = (JSONArray) jsonobj_1.get(“address_components”);
System.out.println(“Elements under results array”);
System.out.println(“\nPlace id: ” +jsonobj_1.get(“place_id”));
System.out.println(“Types: ” +jsonobj_1.get(“types”));
//Get data for the Address Components array
System.out.println(“Elements under address_components array”);
System.out.println(“The long names, short names and types are:”);
for(int j=0;j<jsonarr_2.size();j++)
{
//Same just store the JSON objects in an array
//Get the index of the JSON objects and print the values as per the index
JSONObject jsonobj_2 = (JSONObject) jsonarr_2.get(j);
//Store the data as String objects
String str_data1 = (String) jsonobj_2.get(“long_name”);
System.out.println(str_data1);
String str_data2 = (String) jsonobj_2.get(“short_name”);
System.out.println(str_data2);
System.out.println(jsonobj_2.get(“types”));
System.out.println(“\n”);
}
}
Here is the GitHub link to help you out get started parsing data from an API.
Published at DZone with permission of Soumyajit Basu, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments