DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • What Is API-First?
  • Building REST API Backend Easily With Ballerina Language
  • Aggregating REST APIs Calls Using Apache Camel
  • Choosing a Library to Build a REST API in Java

Trending

  • Stateless vs Stateful Stream Processing With Kafka Streams and Apache Flink
  • Breaking Bottlenecks: Applying the Theory of Constraints to Software Development
  • Intro to RAG: Foundations of Retrieval Augmented Generation, Part 1
  • *You* Can Shape Trend Reports: Join DZone's Software Supply Chain Security Research
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. How to Parse JSON Data From a REST API Using a Simple JSON Library

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.

By 
Soumyajit Basu user avatar
Soumyajit Basu
DZone Core CORE ·
Updated May. 31, 17 · Tutorial
Likes (14)
Comment
Save
Tweet
Share
685.5K Views

Join the DZone community and get the full member experience.

Join For Free

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

JSON API Data (computing) REST Web Protocols Library

Published at DZone with permission of Soumyajit Basu, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • What Is API-First?
  • Building REST API Backend Easily With Ballerina Language
  • Aggregating REST APIs Calls Using Apache Camel
  • Choosing a Library to Build a REST API in Java

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!