Read Data from JSON file Using JAVA – Devstringx

Back to Blog
Feature image for Read Data from Json

Read Data from JSON file Using JAVA – Devstringx

Read Data from Json File Using Java

In JAVA development, Reading data from a JSON file is an ordinary task as it is one of the widely used data interchange formats and is lightweight and language-independent, particularly when it comes to dealing with APIs, configurations, files, or data exchange.

Prerequisites

This segment contains the prerequisites for working with JSON in JAVA, inclusive of basic knowledge of Java programming, its development environment, as well as the required JSON libraries.

The Process to Read JSON Data

Kindly follow the below steps & process to read data from Json File:-

  • Setting up

Before anything else, make sure we have all the necessary tools that are Java development kit (JDK) installed.

Always crosscheck the latest JDK from the official Oracle website and install it accordingly. (as per your operating system)

  • Adding JSON Library

For JSON handling, we need to add a JSON library as JAVA development has built-in support. It’s mandatory at first to add a JSON library to parse and manipulate JSON data.

In this blog, we will use the JSON library, which has efficient JSON processing capabilities. (as we have multiple popular libraries available like Jackson, JSON.org, and Gson.)

Steps to Read JSON Data

Make sure you have the necessary setup, Now let’s proceed towards reading JSON data.

The following set of our mentioned below:

  • Reading

Initially, you need to load the file for JSON data. Now, use JAVA’s input or output classes, namely fileReader or BufferedReader, to read the content.

  • Parse JSON

Now you need to parse the JSON data into suitable JAVA object representations. Jsonfactory and ObjectMapperwhere are a few examples of multiple classes and methods for parsing JSON. (provided by Jackson)

These classes can help us to create object representations of JSON data.

  • Access to JSON Value

As soon as the JSON data is parsed into JAVA objects, one can access its values using suitable methods and classes.

For example, you can retrieve values by accessing the corresponding keys using Jsonobject on Jsonnode classes if you have a JSON object with key-value pairs.

  • Handling Arrays

JSON arrays include ordered lists of values. To read JSON arrays, you need to recapitulate over the array elements and access each value independently.

Note– To handle JSON arrays in Java Jackson provides the following classes:-

  • ArrayNode
  • JsonArray

Exceptions and Error Handling

It’s mandatory and crucial to handle potential errors and expectations delicately. It can be failed on various grounds; such as malformed, Jason, or missing keys. Also, validate to implement error handling mechanisms to handle such scenarios and share valuable, informative feedback to the user.

Testing and validation: To cross-verify the fidelity of your Json reading implementation, execute thorough testing and validation. For example, create test cases with different JSON inputs, and try them out with valid and invalid data, to double-check that your code handles them correctly.

NOTE-  Consider JUnit, Json schema for verifying the structure of your Json data.

Read JSON from the file

Firstly we have to update pom.xml with json-simple maven dependency.

pom.xml

<dependency>

    <groupId>com.googlecode.json-simple</groupId>

    <artifactId>json-simple</artifactId>

    <version>1.1.1</version>

</dependency>

readjsonfile.json -> File with .json extension in the system

Create Java Class

package web.tests.admin;

import java.io.*;

import java.util.*;

import org.json.simple.*;

import org.json.simple.parser.*;

public class jsonreader {           

   public static void main(String[] args) {

  // Read data from file

JSONParser parser = new JSONParser(); // json parser used for read-only access to json data

try {

Object obj = parser.parse(new FileReader("C:/Users/Documents/readjsonfile.json"));  //Read json file path where json file in system

         JSONObject jsonObject = (JSONObject)obj;

         String name = (String)jsonObject.get("Name");

         String course = (String)jsonObject.get("Course");

         JSONArray subjects = (JSONArray)jsonObject.get("Subjects");

         System.out.println("Name: " + name);

         System.out.println("Name: " + jsonObject.get("Name"));

         System.out.println("Course: " + course);

         System.out.println("Subjects:");

         Iterator iterator = subjects.iterator(); // iterator used for cycle through arguments which are present in file or collection

         while (iterator.hasNext())

{

            System.out.println(iterator.next());

         }

      } catch(Exception e) {

         e.printStackTrace();

      }

   }

}

Java Example to Read JSON Data from a Particular Path Location

Example: C:\Users\ABC\Documents\API_testing\jsonex\\sample.json

{
     "lastName": "Smith",
    "address":{
        "streetAddress": "21 2nd Street",
         "city": "New York",
         "state": "NY",
         "postalCode":10021
    },
     "age": 25,
     "phoneNumbers":[
            {
            "type": "home", "number": "212 555-1234"
            },
         {
            "type": "fax", "number": "212 555-1234"
         }
     ],
     "firstName": "John"
}

Code in Java to read JSON Data

We have to use the below code in Java to read the above JSON data

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import io.restassured.path.json.JsonPath;

class JsonExample 
    public static void main(String args[]) {
JsonPath ss = new JsonPath(new String(		Files.readAllBytes(Paths.get("C:\\Users\\ABC\\Documents\\API_testing\\jsonex\\sample.json"))));
    String name1 = ss.getString("lastName");
    System.out.println(name1);
    }
}

Advantages

Below mentioned are a few advantages of the given topic.

Reading data from JSON using  JAVA provides several advantages such as language integration, strong typing and error handling, robust ecosystem, performance, Rich tooling and Documentation, and also community support.

The above-mentioned benefits make JAVA a marketable choice for developers when it comes to working with  JSON and its application.

Conclusion

Encapsulate the key features covered in the blog post, and it gives prominence to the importance of effective reading of JSON data in JAVA. Also, encourages the reader to explore more and utilize the knowledge acquired in their own projects.

By this active approach, one will be equipped with the skills to expertly work with JSON data and incorporate it into your Java application.

 

 

Share this post

Back to Blog