How to Read a JSON File in Java

Reading a JSON File in Java

JSON (JavaScript Object Notation) is a popular way of storing and exchanging data on the web. It is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate. JSON data is stored in text format, making it ideal for transmitting data across the web. Java, being one of the most popular programming languages, provides a simple way of reading JSON files. In this article, we will guide you on how to read a JSON file in Java.

Before we dive into reading a JSON file in Java, let’s first understand what JSON is and how it is structured.

Understanding JSON

JSON is a text format for storing and exchanging data. It is similar to XML, but JSON is simpler and easier to read and write. JSON consists of key-value pairs, where each key is a string, and the value can be of any data type, such as string, number, boolean, array, or another JSON object.

A JSON object is enclosed in curly braces {} and consists of a set of key-value pairs. Each key is separated from its value by a colon (:), and each key-value pair is separated from the next by a comma (,). Here’s an example of a JSON object:

{
   "name": "John",
   "age": 30,
   "city": "New York"
}

In the above example, the JSON object has three key-value pairs: name, age, and city. The value of the name key is "John", the value of the age key is 30, and the value of the city key is "New York".

Reading a JSON File in Java

Now that we have a basic understanding of JSON, let’s see how we can read a JSON file in Java. To read a JSON file in Java, we will use a library called JSON.simple. JSON.simple is a lightweight Java library for parsing and generating JSON data.

To use JSON.simple, you need to add the following dependency to your project:


   com.googlecode.json-simple
   json-simple
   1.1.1

Once you have added the dependency, you can start reading JSON files in your Java code. Here’s how:

Step 1: Create a FileReader Object

The first step is to create a FileReader object that will read the JSON file. The FileReader constructor takes a file name or a file object as its parameter. Here’s an example:

import java.io.FileReader;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class ReadJSONFile {
   public static void main(String[] args) {
      JSONParser parser = new JSONParser();

      try (FileReader reader = new FileReader("data.json")) {
         //Read JSON file
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

In the above example, we have imported the necessary classes and created an instance of the JSONParser class. We have also created a FileReader object that will read the data.json file.

Step 2: Parse the JSON File

The next step is to parse the JSON file using the JSONParser class. The parse method of the JSONParser class takes the FileReader object as its parameter and returns an Object. We need to cast the returned Object to JSONObject to be able to access the JSON data. Here’s an example:

import java.io.FileReader;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class ReadJSONFile {
   public static void main(String[] args) {
      JSONParser parser = new JSONParser();

      try (FileReader reader = new FileReader("data.json")) {
         //Read JSON file
         Object obj = parser.parse(reader);
         JSONObject jsonObj = (JSONObject) obj;
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

In the above example, we have parsed the JSON file using the parse method of the JSONParser class and cast the returned Object to JSONObject.

Step 3: Access the JSON Data

The final step is to access the JSON data. We can access the JSON data using the get method of the JSONObject class. The get method takes the key as its parameter and returns the value associated with the key. Here’s an example:

import java.io.FileReader;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class ReadJSONFile {
   public static void main(String[] args) {
      JSONParser parser = new JSONParser();

      try (FileReader reader = new FileReader("data.json")) {
         //Read JSON file
         Object obj = parser.parse(reader);
         JSONObject jsonObj = (JSONObject) obj;

         //Get data
         String name = (String) jsonObj.get("name");
         long age = (long) jsonObj.get("age");
         String city = (String) jsonObj.get("city");

         //Print data
         System.out.println("Name: " + name);
         System.out.println("Age: " + age);
         System.out.println("City: " + city);
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

In the above example, we have accessed the JSON data using the get method of the JSONObject class and printed the data to the console.

Conclusion

In this article, we have learned how to read a JSON file in Java using the JSON.simple library. We have covered the basics of JSON and its structure, and we have provided a step-by-step guide on how to read a JSON file in Java. With this knowledge, you can now easily read JSON files and access their data in your Java programs.

Leave a Comment

Your email address will not be published. Required fields are marked *