How To Read A Json File In Java

5 min read

Learning how to read a JSON file in Java is an essential skill for modern developers working with web services, configuration files, and data exchange formats. JSON, short for JavaScript Object Notation, has become the universal language of APIs, and Java developers need reliable tools to parse, extract, and manipulate this data efficiently. Whether you are building a mobile application, a backend service, or a desktop tool, understanding the best way to read a JSON file in Java will save you time and prevent common parsing errors.

Why Reading JSON Files Matters in Java

JSON is everywhere. From REST API responses to application settings, this lightweight format allows systems to communicate without relying on complex XML structures. In Java, reading a JSON file means converting raw text into usable Java objects so your program can access values, iterate over arrays, and perform business logic Surprisingly effective..

Without proper JSON handling, developers often resort to string manipulation, which is error-prone and difficult to maintain. By using dedicated libraries, you can transform a JSON file into strongly typed objects, validate structure, and handle nested data with minimal effort.

Prerequisites and Setup

Before you can read a JSON file in Java, you need to decide which library to use. Java does not include a built-in JSON parser in its standard library, so most developers rely on third-party tools Nothing fancy..

Choosing the Right Library

The three most popular options are:

  • Jackson – A powerful, feature-rich library widely used in enterprise applications and Spring Framework projects.
  • Gson – Google’s lightweight library, ideal for simple serialization and deserialization tasks.
  • org.json – A straightforward, dependency-free option suitable for small projects and quick scripts.

Adding Dependencies to Your Project

If you use Maven, add the relevant dependency to your pom.xml file. For Jackson, the configuration looks like this:


    com.fasterxml.jackson.core
    jackson-databind
    2.15.2

For Gson, add:


    com.google.code.gson
    gson
    2.10.1

Gradle users can include similar entries in their build.gradle file. Even so, if you prefer org. json, you can download the single JAR file and add it to your classpath without managing transitive dependencies And it works..

Creating a Sample JSON File

To follow along, create a file

Creating a Sample JSON File

Below is a small, yet realistic JSON document you can drop into your project’s resources folder (or any directory your code can read). It contains a list of users, each with an id, name, email, and a nested address object And that's really what it comes down to. Turns out it matters..

{
  "users": [
    {
      "id": 1,
      "name": "Alice Johnson",
      "email": "alice@example.com",
      "address": {
        "street": "123 Maple St",
        "city": "Seattle",
        "zip": "98101"
      }
    },
    {
      "id": 2,
      "name": "Bob Smith",
      "email": "bob@example.com",
      "address": {
        "street": "456 Oak Ave",
        "city": "Portland",
        "zip": "97201"
      }
    }
  ],
  "total": 2
}

Save this as users.json under src/main/resources (Maven) or any accessible path if you’re using a plain Java project It's one of those things that adds up..


Reading JSON with Jackson

Jackson’s ObjectMapper can read raw JSON into Java objects with minimal boilerplate. First, define a POJO that mirrors the JSON structure Less friction, more output..

// User.java
public class User {
    private int id;
    private String name;
    private String email;
    private Address address;

    // getters and setters
    public int getId() { return id; }
    public void setId(int id) { this.name = name; }
    public String getEmail() { return email; }
    public void setEmail(String email) { this.Because of that, id = id; }
    public String getName() { return name; }
    public void setName(String name) { this. email = email; }
    public Address getAddress() { return address; }
    public void setAddress(Address address) { this.

    @Override
    public String toString() {
        return "User{id=" + id + ", name='" + name + "', email='" + email + "', address=" + address + "}";
    }
}

// Address.java
public class Address {
    private String street;
    private String city;
    private String zip;

    // getters and setters
    public String getStreet() { return street; }
    public void setStreet(String street) { this.street = street; }
    public String getCity() { return city; }
    public void setCity(String city) { this.city = city; }
    public String getZip() { return zip; }
    public void setZip(String zip) { this.

    @Override
    public String toString() {
        return "Address{street='" + street + "', city='" + city + "', zip='" + zip + "'}";
    }
}

// Container POJO for the root object
class UsersContainer {
    private List users;
    private int total;

    // getters and setters
    public List getUsers() { return users; }
    public void setUsers(List users) { this.users = users; }
    public int getTotal() { return total; }
    public void setTotal(int total) { this.total = total; }

    @Override
    public String toString() {
        return "UsersContainer{users=" + users + ", total=" + total + "}";
    }
}

Now, the parsing code:

// JacksonReader.java
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.io.IOException;

public class JacksonReader {
    public static void main(String[] args) {
        ObjectMapper mapper = new ObjectMapper();

        try {
            // Read JSON file into the container POJO
            UsersContainer container = mapper.readValue(
                new File("src/main/resources/users.json"),
                UsersContainer.

            // Print the deserialized object
            System.Consider this: println(container);
            container. In practice, forEach(System. err.Consider this: out::println);
        } catch (IOException e) {
            System. out.getUsers().println("Failed to read JSON with Jackson: " + e.

**What happens under the hood?**  
- `ObjectMapper` automatically maps JSON

JSON fields to Java fields by inspecting the target class at runtime. It uses reflection to locate a no-argument constructor, instantiate the object, and then match JSON keys to fields, setters, or getters. By default, Jackson performs case-insensitive matching and can access private fields directly if no setter is present, though using public accessors is the more common and encapsulated approach.

When Jackson encounters the `users` array in the JSON, it examines the generic type of the `users` field in `UsersContainer`, determines that the collection should contain `User` instances, and deserializes each element recursively. The same recursive process applies to the nested `address` object: Jackson instantiates an `Address`, maps its `street`, `city`, and `zip` fields, and injects the resulting object into the `User` via its setter.

If the JSON contains properties that do not exist in the Java class, Jackson throws an `UnrecognizedPropertyException` unless `FAIL_ON_UNKNOWN_PROPERTIES` is disabled. Similarly, type mismatches—such as a string where an integer is expected—trigger a `MismatchedInputException`. These safeguards make failures explicit early in the parsing process.

Behavior can be customized with annotations. As an example, `@
Just Came Out

Brand New Stories

Similar Ground

More Reads You'll Like

Thank you for reading about How To Read A 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