In this tutorial, you will learn how to read the contents of a JSON file to a Java object using the JSON library. Since this is not the only way to read from a JSON file, you will learn other methods in the coming tutorials.
When testing applications, you will always need test data to test your application. The best approach to create test data for your application is by reading from a file.
The file formats that you can read from include XML, JSON, and text files. Since JSON is the most common format of data exchange. Learning how to read from a JSON file will come in handy.
Project setup
This blog has a tutorial that shows you how to create a Maven project in IntelliJ. Use the tutorial to create a new project.
To add the JSON library to your project. Copy and paste the following XML into the file named pom.xml.
<dependencies> <!-- https://mvnrepository.com/artifact/org.json/json --> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20230618</version> </dependency> </dependencies>
The following image shows where the XML gets added in the pom.xml file.

Press CTRL+SHIFT+O to load the Maven changes. Maven will download the JSON library and add it to the project’s classpath.
Create a JSON file
Create a file named student.json in the root folder and copy and paste the following JSON data into the file.
[ { "studentId": 1, "firstName": "john", "lastName": "doe", "email": "john@javawhizz.com" }, { "studentId": 2, "firstName": "mary", "lastName": "public", "email": "mary@javawhizz.com" } ]
The student.json file contains an array with two student objects. The student objects have the fields student ID, first name, last name, and email.
Create a Student class
Create a file named Student.java in your main package and copy and paste the following code into the file. Note that your package name might be different from the one in the code depending on the name you used.
package com.javawhizz; public class Student { private final Long studentId; private final String firstName; private final String lastName; private final String email; public Student(Long studentId, String firstName, String lastName, String email){ this.studentId = studentId; this.firstName = firstName; this.lastName = lastName; this.email = email; } @Override public String toString() { return "Student{" + "studentId=" + studentId + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", email='" + email + '\'' + '}'; } }
The Student.java file creates an instance of a student and we will use this class to create Student objects. Each student object in the JSON file will have a new Student object in Java.
You will use the Student()
method to create Java objects. Pass all the fields in the class as the parameters of the method.
The toString()
method creates a string representation of a student object. The method will help you to output a string representation of the Java objects.
Read JSON to a Java Object
Create a file named JSONFileReader.java and copy and paste the following code into the file.
package com.javawhizz; import org.json.JSONArray; import org.json.JSONObject; import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; import java.util.List; import java.util.Objects; public class JSONFileReader { public List<Student> readStudentsFromJSONFile(){ JSONArray jsonArray = null; try(FileReader fileReader = new FileReader("student.json"); BufferedReader bufferedReader = new BufferedReader(fileReader)) { StringBuilder stringBuilder = new StringBuilder(); String jsonString; while ((jsonString = bufferedReader.readLine()) != null){ stringBuilder.append(jsonString); } String jsonStringContent = stringBuilder.toString(); jsonArray = new JSONArray(jsonStringContent); }catch (Exception e){ e.printStackTrace(); } List<Student> students = new ArrayList<>(); JSONArray array = Objects.requireNonNull(jsonArray); for (int i = 0; i < array.length(); i++) { JSONObject student = jsonArray.getJSONObject(i); long studentId = student.getLong("studentId"); String firstName = student.getString("firstName"); String lastName = student.getString("lastName"); String email = student.getString("email"); Student theStudent = new Student( studentId, firstName, lastName, email); students.add(theStudent); } return students; } }
The class contains only one method that defines the logic to read the JSON file to Java objects.
Create an instance of the FileReader
class using the try-with-resource syntax. The file reader will help you to read data from the JSON file.
Additionally, create another instance of BufferedReader
in the try-with-resource. Pass the reference of the file reader as the argument. The buffered reader helps to prevent direct reading from the file which is very inefficient.
Inside the method, define a new instance of StringBuilder
. You will use this builder to create a string representation of the JSON data.
To read the JSON data, call the readLine()
method of the buffered reader. Append the string returned to a temporary string using the string builder.
Since you expect an array, create a new instance of JSONArray and pass string builder as the argument. additionally, call the toString()
method of string builder to get the data as a string.
The JSON array returned contains an array of JSON objects. Use a for loop to get the JSON objects in the array by calling the getJSONObject()
then pass the index as the argument.
For each JSONObject
returned, get the student ID, first name, last name, and email. Since the student ID is Long, use the method getLong()
to get the value.
Use the method getString()
for the other fields since they are of type String. To create a student object, pass the student ID, first name, last name, and email as the argument of a new student.
Finally, add each created student to a new ArrayList
and return the list.
Run the application
When creating the Maven project, IntelliJ generated a file named Main.java. Copy and paste the following code into the file.
package com.javawhizz; public class Main { public static void main(String[] args) { JSONFileReader JSONFileReader = new JSONFileReader(); JSONFileReader.readStudentsFromJSONFile() .forEach(System.out::println); } }
To verify that the JSON data gets read to Java objects. First, create an instance of the JSONFileReader
.
Since the method readStudentsFromJSONFile()
defined in the class returns a list. Chain the call to the method with a call to the forEach()
method.
Finally, pass a method reference of the println()
statement as the argument of forEach()
. This will print the contents of the list to the console. The output of your IDE should be as shown below.
Output
Student{studentId=1, firstName='john', lastName='doe', email='john@javawhizz.com'} Student{studentId=2, firstName='mary', lastName='public', email='mary@javawhizz.com'}
Conclusion
In this tutorial, you have learned how to read the contents of a JSON file to a Java object using the JSON library.
In the coming tutorials, you will learn how to read from other file formats such as XML. This is important because you might encounter some legacy applications that use XML.
As mentioned in the introduction section, this is not the only approach to reading from a JSON file in Java. You will also learn how to use other approaches in the coming tutorials.
Happy Hacking!
0 Comments