Open In App

How to Read and Write JSON Files in Java?

JSON (JavaScript Object Notation) is simple but powe­rful. It helps the server and the client to share information. Applications like­ Java use special tools, or libraries, that re­ad JSON. In Java, some libraries make it easy to read and write JSON files. One popular library is Jackson.

In this article, we will learn how to read and write JSON files in Java.



Prerequisites:

The proje­ct needs the Jackson library. You can add this manually by downloading the JAR files or using a build tool like­ Maven or Gradle.

Steps to Read and Write JSON files

Now, let’s create a simple Java project using Visual Studio Code and Maven.



Step 1: Create a Java Maven Project

Open the command prompt and run the following commands to initialize a new Maven project.

mvn archetype:generate
-DgroupId=com.example
-DartifactId=json-java1
-DarchetypeArtifactId=maven-archetype-quickstart
-DinteractiveMode=false

This command will generate a basic Maven project structure. Below we can see the Maven project builds successfully.

Step 2: Add Jackson Dependency

Open the pom.xml file in the project folder then add the Jackson dependency into it.

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.16.1</version>
</dependency>
</dependencies>


Save the pom.xml file.

Step 3: Create Java Files

In the src/main/java/com/example folder, create two Java files: JsonFileReader.java and JsonFileWriter.java.

JsonFileWriter.java:




package com.example;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.File;
import java.io.IOException;
public class JsonFileWriter {
    public static void main(String[] args) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectNode jsonNode = objectMapper.createObjectNode();
        jsonNode.put("name", "Abul Hasan");
        jsonNode.put("age", 23);
        jsonNode.put("city", "Lucknow");
        jsonNode.put("state", "Uttar Pradesh");
        jsonNode.put("country", "India");
        objectMapper.writeValue(new File("mydata.json"), jsonNode);
    }
}

Explanation of the above Program:

JsonFileReader.java:




package com.example;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.io.IOException;
public class JsonFileReader {
    public static void main(String[] args) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(new File("mydata.json"));
        String name = jsonNode.get("name").asText();
        int age = jsonNode.get("age").asInt();
        String city = jsonNode.get("city").asText();
        String state = jsonNode.get("state").asText();
        String country = jsonNode.get("country").asText();
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("City: " + city);
        System.out.println("State: " + state);
        System.out.println("Country: " + country);
    }
}

Explanation of the above Program:

Step 4: Run the Program

To run the project, use below maven commands.

mvn compile
mvn exec:java -Dexec.mainClass="com.example.JsonFileWriter"
mvn exec:java -Dexec.mainClass="com.example.JsonFileReader"

Note: The project can be direct run from run icon of the visual studio code or any of the IDE.

Output demo:

Conclusion

This Java code uses the Jackson library. It shows how to write and read JSON files. The JsonFileWriter class makes a JSON object and stores it in a file. The JsonFileReader class reads the JSON data from the file. It turns it into a JsonNode and pulls out specific values. We use ObjectMapper and ObjectNode to make it easier to flip between Java objects and JSON. Things covered include adding key-value pairs and writing files. We also include extracting data afterwards. This is a basic guide for read and write json in Java and helps how to use JSON files in Java.


Article Tags :