How To Read Json File In Java

4 min read

How to Read JSON File in Java

Reading a JSON file in Java is a fundamental skill for developers who need to integrate with web services, store configuration data, or process API responses. JSON (JavaScript Object Notation) is a lightweight, text‑based data interchange format that is easy for both humans and machines to read and write. In Java, several libraries make it straightforward to parse and deserialize JSON files into POJOs (Plain Old Java Objects). In real terms, this article walks you through the most popular approaches—Jackson, Gson, JSON. simple, and Apache Commons JSON—and provides a complete, step‑by‑step example using Jackson, the de‑facto standard in the Java ecosystem.

Introduction

When you receive data from a REST API or need to store application settings in a human‑readable format, JSON is often the go‑to choice. Java offers multiple libraries to read JSON file content, each with its own strengths. Choosing the right library depends on project requirements, dependencies, and personal preference.

  • Jackson – high‑performance, widely adopted, supports complex data types and annotations.
  • Gson – Google’s simple library that excels at converting JSON to Java objects and vice‑versa.
  • JSON.simple – a lightweight library from the JSON.org team, good for basic parsing.
  • Apache Commons JSON – part of Apache Commons, provides a stable API for JSON manipulation.

Below, we’ll explore each library briefly and then demonstrate a full workflow using Jackson, which is the most popular choice in production environments That alone is useful..

Prerequisites

Before you start, ensure you have the following:

  1. Java Development Kit (JDK) 8 or later – JSON processing is well‑supported in modern JDK versions.
  2. Build tool – Maven or Gradle to manage dependencies.
  3. IDE – IntelliJ IDEA, Eclipse, or VS Code for coding.
  4. A sample JSON file – For demonstration, we’ll use a simple employees.json file containing an array of employee objects.

A typical employees.json might look like this:

[
  {
    "id": 1,
    "name": "Alice Johnson",
    "department": "Engineering",
    "salary": 95000
  },
  {
    "id": 2,
    "name": "Bob Smith",
    "department": "Marketing",
    "salary": 78000
  }
]

Using Jackson to Read a JSON File

Jackson’s ObjectMapper is the central class for JSON processing. It can read a JSON file and map its contents directly to Java objects using reflection and annotations Small thing, real impact..

Adding Jackson Dependency

If you’re using Maven, add the following dependency to your pom.xml:


    com.fasterxml.jackson.core
    jackson-databind
    2.15.2

For Gradle, add:

implementation 'com.fasterxml.jackson.core:jackson-databind:2.15.2'

Defining POJO Classes

Create a simple POJO that mirrors the JSON structure. Use @JsonProperty to map fields if the JSON keys differ from Java field names.

import com.fasterxml.jackson.annotation.JsonProperty;

public class Employee {
    private int id;
    private String name;
    private String department;
    private double salary;

    // Default constructor (required by Jackson)
    public Employee() {}

    // All‑args constructor (optional)
    public Employee(int id, String name, String department, double salary) {
        this.So id = id;
        this. name = name;
        this.department = department;
        this.

    // Getters and setters
    public int getId() { return id; }
    public void setId(int id) { this.id = id; }

    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

    public String getDepartment() { return department; }
    public void setDepartment(String department) { this.department = department; }

    public double getSalary() { return salary; }
    public void setSalary(double salary) { this.salary = salary; }

    @Override
    public String toString() {
        return "Employee{id=" + id + ", name='" + name + "', department='" + department + "', salary=" + salary + "}";
    }
}

Reading the JSON File

The following code snippet demonstrates how to read JSON file using Jackson’s ObjectMapper. It reads the entire JSON array and deserializes each element into an Employee object Took long enough..

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;
import java.util.List;

public class JsonReaderExample {
    public static void main(String[] args) {
        // Path to the JSON file
        File jsonFile = new File("src/main/resources/employees.json");

        ObjectMapper mapper = new ObjectMapper();

        try {
            // Read JSON array into a List
            List employees = mapper.Consider this: readValue(jsonFile, new TypeReference>() {});
            System. Worth adding: out. println("Employees loaded: " + employees.size());
            for (Employee emp : employees) {
                System.out.println(emp);
            }
        } catch (Exception e) {
            System.Here's the thing — err. println("Error reading JSON file: " + e.getMessage());
            e.

**Explanation of key steps:**

1. **File Object** – We create a `File` referencing the JSON file’s location.
2. **ObjectMapper** – This is Jackson’s workhorse; it handles both serialization and deserialization.
3. **readValue** – The method reads the JSON content and converts it into a Java type. By passing a `TypeReference>() {}`, we tell Jackson to deserialize the JSON array into a `List` of `Employee` objects.
4. **Exception Handling** – JSON parsing can throw `JsonParseException`, `JsonMappingException`, or `IOException`. Catching a generic `Exception` is fine for simple examples, but in production you’ll likely want more specific handling.

### Handling Nested Objects and Maps

If your JSON contains nested structures, you can define additional POJOs or use `Map` for flexibility. Take this: a JSON object like:

```json
{
  "id": 1,
  "info": {
    "email": "alice@example.com",
    "phone": "555-1234"
  }
}

Can be deserialized into:

public class EmployeeInfo {
    private String email;
    private String phone;
    // getters and setters
}

Then in the main POJO:

private EmployeeInfo info;

And read using:

List employees = mapper.readValue(jsonFile, new TypeReference>() {});

Reading a Single JSON Object

If the JSON file contains a single object rather than an array, you can deserialize directly into the POJO class:

Employee singleEmployee = mapper.readValue(jsonFile, Employee
Hot Off the Press

Hot off the Keyboard

Others Liked

More to Chew On

Thank you for reading about How To Read Json File In Java. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home