How to Read and Write JSON Files in Java?
Last Updated :
10 Oct, 2024
JSON (JavaScript Object Notation) is simple but powerful.. It helps the server and the client to share information. Applications like Java use special tools, or libraries, that read 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 project 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:
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:
- We declare that the class is part of the com.example package.
- After that, we import classes we need to handle JSON with the Jackson library.
- Jackson's ObjectMapper provides us functionality in writing JSON. ObjectNode is used a JSON object.
- Then we created a public JsonFileWriter class with a main method, and it throws an IOException. This shows that input/output exceptions could happen.
- Then an ObjectMapper instance is created. It coverting Java objects into JSON.
- Then an empty ObjectNode is created next. It helps structure of the JSON object.
- Then some Key-value pairs added to the JSON object. The put method adds them in. Put can add Strings, numbers, and other types.
- At the last, ObjectMapper's writeValue method is used. It writes the JSON object to a file called "mydata.json". This can sometimes cause an IOException, so it's declared in the main method's throws clause.
JsonFileReader.java:
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:
- We declare that the class is part of the com.example package.
- After that, we import classes we need to handle JSON with the Jackson library.
- Jackson's ObjectMapper provides us functionality in reading JSON. ObjectNode is used a JSON object.
- Then we created a public JsonFileReader class with a main method, and it throws an IOException. This shows that input/output exceptions could happen.
- Then an ObjectMapper instance is created. It coverting Java objects into JSON.
- Then readTree method is used to read the contents of the JSON file "mydata.json" and converts it into a JsonNode object.
- The get method is used to extract values from the JsonNode. The .asText() and .asInt() methods are used to convert the values to the appropriate Java types.
- And at last, the extracted values are printed to the console.
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.
Similar Reads
How to Read and Write Binary Files in Java?
The Binary files contain data in a format that is not human-readable. To make them suitable for storing complex data structures efficiently, in Java, we can read from the write to binary files using the Input and Output Streams. In this article, we will learn and see the code implementation to read
2 min read
Java Program to Write into a File
FileWriter class in Java is used to write character-oriented data to a file as this class is character-oriented because it is used in file handling in Java. There are many ways to write into a file in Java as there are many classes and methods which can fulfill the goal as follows: Using writeString
6 min read
How to Read and Write Files Using the New I/O (NIO.2) API in Java?
In this article, we will learn how to read and write files using the new I/O (NIO) API in Java. For this first, we need to import the file from the NIO package in Java. This NIO.2 is introduced from the Java 7 version. This provides a more efficient way of handling input and output operations compar
3 min read
Write HashMap to a Text File in Java
The HashMap class in Java implements the Serializable interface so that its objects can be written or serialized to a file using the ObjectOutputStream. However, the output file it produces is not in the human-readable format and may contain junk characters. Serialization: It is a process of writing
3 min read
How to Zip and Unzip Files in Java?
In Java Programming we have a lot of features available for solving real-time problems. Here I will explain how to Zip files and How to Unzip files by using Java Programming. Mostly zip and unzip files are used for zip the files for save storage, easy to share, and other purposes. In this article, w
3 min read
How to Lock a File in Java?
In Java, file locking involves stopping processes or threads from changing a file. It comes in handy for threaded applications that require simultaneous access, to a file or to safeguard a file from modifications while it's being used by our application. When reading or writing files we need to make
2 min read
How to Convert a HashSet to JSON in Java?
In Java, a HashSet is an implementation of the Set interface that uses a hash table to store elements. It allows fast lookups and does not allow duplicate elements. Elements in a HashSet are unordered and can be of any object type. In this article, we will see how to convert a HashSet to JSON in Jav
2 min read
How to Read a File From the Classpath in Java?
Reading a file from the classpath concept in Java is important for Java Developers to understand. It is important because it plays a crucial role in the context of Resource Loading within applications. In Java, we can read a file from the classpath by using the Input Stream class. By loading the cla
3 min read
How to Serialize and Deserialize a TreeMap in Java?
In Java, serialization is implemented by using the Serializable Interface. The use of the TreeMap class is a simple way to serialize and deserialize the objects. It is a component of the Java Collections framework. For writing and reading objects, we will be using the ObjectOutputStream and ObjectIn
2 min read
How to Create a File with a Specific Owner and Group in Java?
Java is a basic tool that does not directly let you choose who owns a file or which group it belongs to when you create it. You have to rely on other methods or external libraries if you need to control these aspects. In this article, we will learn How to create a file with a specific owner and grou
3 min read