Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To read a modest JSON file in Java 11 or later, use Files.readString(Path) to load its UTF-8 text, then pass that text to a JSON library such as Jackson or Gson. Reading the file and parsing its JSON are separate operations: Java reads bytes and decodes text; the library validates the JSON and converts it into Java objects or a tree. For large files, use a streaming parser so you do not need to hold the entire document in memory.

Choose how to parse the file

Pick the approach based on file size, whether you need the entire document, and whether you want typed Java objects. The examples below use Jackson and Gson; either can parse JSON, but their APIs and dependency versions differ. If your project already uses one, using that library is usually the simplest choice.

Approach Use it when Trade-off
Read the whole file, then parse The file is modest in size and a concise implementation is useful. The full text is held in memory before parsing.
Bind to Java objects You know the expected structure and want fields represented by Java types. The JSON structure must fit the target type.
Parse into a tree You want to inspect or navigate fields without defining a class for every part. The parsed tree is held in memory.
Stream tokens The input is large or you need to process selected values incrementally. You write more explicit iteration logic.

Read a small JSON file with Java 11 or later

Files.readString(Path) reads the file into a string, decodes it as UTF-8 by default, and closes the file after reading. It was introduced in Java 11 and is intended for convenient whole-file reads, not exceptionally large inputs. If the string cannot fit in memory, the call can fail with OutOfMemoryError. [Oracle Files API]

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class ReadJson {
    public static void main(String[] args) throws IOException {
        Path path = Path.of("data.json");
        String json = Files.readString(path);

        // Parse json with Jackson or Gson, as shown below.
    }
}

This first step can throw IOException, for example when the file cannot be accessed or its bytes cannot be decoded. Keep that failure distinct from errors reported by the JSON parser.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Parse JSON into a typed Java object with Jackson

Define a class that reflects the JSON fields you need, then ask Jackson’s ObjectMapper to create an instance. For example, given {"name":"Ada","active":true}:

import com.fasterxml.jackson.databind.ObjectMapper;

public class Person {
    public String name;
    public boolean active;
}

// After reading the file into the json string:
ObjectMapper mapper = new ObjectMapper();
Person person = mapper.readValue(json, Person.class);
System.out.println(person.name);

Jackson’s databinding API maps JSON content to a requested Java type. It also supports reading directly from files and other input sources; consult the documentation for the major version used by your project, because Jackson 3.x and older 2.x examples may differ. [Jackson databind README] [Jackson 3.x ObjectMapper]

If you choose file or stream input instead of first creating a string, make resource ownership explicit. Close streams or readers that your code creates, typically with try-with-resources.

Parse JSON with Gson

Gson can also deserialize a JSON string into a Java class. To parse directly from a file-backed reader, use try-with-resources so the reader is closed even if parsing fails:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import com.google.gson.Gson;
import java.io.Reader;
import java.nio.file.Files;
import java.nio.file.Path;

Gson gson = new Gson();
try (Reader reader = Files.newBufferedReader(Path.of("data.json"))) {
    Person person = gson.fromJson(reader, Person.class);
}

For a parameterized type such as List<Person>, preserve the element type with Gson’s TypeToken. A raw Collection.class does not tell Gson what type each element should be. [Gson User Guide]

import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.List;

Type personListType = new TypeToken<List<Person>>() {}.getType();
try (Reader reader = Files.newBufferedReader(Path.of("people.json"))) {
    List<Person> people = gson.fromJson(reader, personListType);
}

Use a JSON tree when the structure is not a fixed class

A tree lets you inspect fields by name without binding the whole document to a custom Java class. With Jackson, parse into a JsonNode and navigate the values you need:

import com.fasterxml.jackson.databind.JsonNode;

JsonNode root = mapper.readTree(json);
String name = root.path("name").asText();
boolean active = root.path("active").asBoolean();

A tree is useful when fields are optional or the input shape varies, but it still creates an in-memory representation. Jackson distinguishes an input with no content from a JSON literal null; decide how your application should handle each before using the result. [Jackson 3.x ObjectMapper]

Stream large files instead of loading them all at once

For a large document, avoid Files.readString if holding the entire text is unsuitable. Gson’s JsonReader provides token-based reading, and Jackson also supports parsing from streams. Streaming lets an application process values incrementally rather than first building a complete string or tree. It requires explicit traversal logic, and the right implementation depends on the document structure. [Gson User Guide] [Jackson databind README]

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Streaming does not by itself define how much input your application should accept. Set appropriate size or record limits for the application, and handle parser errors as well as I/O errors.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Handle file, JSON, and mapping errors separately

  • File access or decoding failure: Java reports an IOException when the file cannot be read or its bytes cannot be decoded as text.
  • Malformed JSON: A JSON parser reports a parsing or stream-read error when the input does not follow JSON syntax.
  • Valid JSON with an incompatible shape: Binding can fail when the JSON structure does not fit the requested Java type. Jackson documents parsing and databinding failures separately. [Jackson databind README]
  • Empty input or JSON null: These are not necessarily equivalent to a library. Define expected behavior and validate the parsed result before dereferencing it.

Do not catch every failure as though it meant the same thing. Report file problems as I/O failures and malformed or incompatible content as parsing or mapping failures; this makes it easier to find whether the cause is a path, encoding, JSON syntax, or expected data shape.

Close streams and readers you open

FileInputStream and reader types implement AutoCloseable. Use try-with-resources whenever your code explicitly opens one; Java closes it when the block exits, including when an exception interrupts the block. [Oracle FileInputStream API] [Oracle try-with-resources tutorial]

try (var reader = Files.newBufferedReader(Path.of("data.json"))) {
    // Parse from reader here.
}

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.