How To Read Json From File In Java

9 min read

Reading JSON data from a file in Java is a common task for developers who need to exchange structured information between applications. This guide shows you how to read JSON from a file in Java, covering the necessary libraries, step‑by‑step procedures, and practical tips to avoid typical errors. By following the instructions below, you will be able to load, parse, and manipulate JSON content with confidence, whether you are building a simple utility or a complex enterprise application.

Prerequisites

Before you start coding, make sure you have the following ready:

  • Java Development Kit (JDK) 8 or higher installed on your system.
  • An IDE or text editor that supports Java editing (e.g., IntelliJ IDEA, Eclipse, VS Code).
  • A JSON file (data.json) containing the data you want to read. The file should be placed in a location accessible to your program, such as the project root or a known absolute path.

Tip: If you are using a build tool like Maven or Gradle, add the required dependencies to your pom.Plus, xml or build. gradle file (see the next sections) Surprisingly effective..

Using the Built‑in javax.json API

Since Java EE 7, the JSON Processing API (javax.json) is part of the standard JDK through the java.json module. This API lets you read JSON without adding external libraries.

Step‑by‑step

  1. Add the module (if you are on JDK 9+). In your module-info.java include:
    requires java.json;
    
  2. Create a Path object pointing to your JSON file:
    import java.nio.file.Paths;
    import java.nio.file.Files;
    
  3. Read all bytes from the file:
    String jsonString = new String(Files.readAllBytes(Paths.get("data.json")));
    
  4. Parse the string using JsonReaderFactory:
    import javax.json.Json;
    import javax.json.JsonReader;
    import javax.json.JsonValue;
    
  5. Read the JSON structure:
    try (JsonReader reader = Json.createReader(jsonString)) {
        JsonValue root = reader.readObject(); // root is the top‑level JSON element
        // Example: iterate over an array named "items"
        if (root.getValueType() == JsonValue.ValueType.OBJECT) {
            JsonObject obj = root.asJsonObject();
            JsonArray items = obj.getJsonArray("items");
            for (JsonValue item : items) {
                System.out.println(item.toString());
            }
        }
    }
    
  6. Handle exceptions with a try‑catch block to manage JsonException and I/O errors.

Why use the built‑in API?

  • No extra dependencies, which keeps the project lightweight.
  • Good for small to medium JSON files where performance is not critical.

Leveraging Popular Third‑Party Libraries

For larger files, better performance, or richer mapping capabilities, most developers prefer Jackson or Gson. Both libraries provide object‑mapper features that convert JSON directly into Java objects (POJOs).

Jackson Example

  1. Add the dependency (Maven):
    
        com.fasterxml.jackson.core
        jackson-databind
        2.15.2
    
    
  2. Define a POJO that matches the JSON structure:
    public class DataRecord {
        private String id;
        private int value;
        // getters and setters
        public String getId() { return id; }
        public void setId(String id) { this.id = id; }
        public int getValue() { return value; }
        public void setValue(int value) { this.value = value; }
    }
    
  3. Read the file:
    import com.fasterxml.jackson.databind.ObjectMapper;
    import java.io.File;
    import java.io.IOException;
    
    public class JsonReaderJackson {
        public static void main(String[] args) throws IOException {
            ObjectMapper mapper = new ObjectMapper();
            DataRecord record = mapper.readValue(file, List.Even so, readValue(new File("data. class);
            System.println("ID: " + record.out.json"), DataRecord.getId() + ", Value: " + record.That's why getValue());
        }
    }
    
    *If the JSON contains an array, use mapper. class) or map to a collection type.

Gson Example

  1. Add the dependency (Gradle):
    implementation 'com.google.code.gson:gson:2.10.1'
    
  2. Parse the JSON:
    import com.google.gson.Gson;
    import com.google.gson.reflect.TypeToken;
    import java.lang.reflect.Type;
    import java.ioReader;
    import java.nio.file.Files;
    import java.nio.file.Path;
    
    public class JsonReaderGson {
        public static void main(String[] args) throws IOException {
            String json = new String(Files.readAllBytes(Path.of("data.json")));
            Gson gson = new Gson();
            // For a simple object
            DataRecord record = gson.fromJson(json, DataRecord.class);
            System.Also, out. println(record.
    
            // For an array of objects
            Type listType = new TypeToken>() {}.Consider this: getType();
            List records = gson. out.forEach(r -> System.fromJson(json, listType);
            records.println(r.
    
    

Comparison

  • Jackson excels in performance and handling complex schemas.
  • Gson offers a simpler API and is easier for quick prototypes.
  • Both libraries automatically handle escaping, data type conversion, and nested structures.

Understanding JSON Structure

JSON is a text‑based format that represents data as objects ({}), arrays ([]), strings, numbers, booleans, and null. When you read JSON from a file, the parser transforms this text into a tree model (DOM) or directly into objects (SAX/StAX). The key concepts are:

  • Object → a collection of name/value pairs, analogous to a Java Map.
  • Array → an ordered list, analogous to a Java List.
  • Value types → primitives that map to Java types (String

Mapping JSON Values to Java Types

When a JSON document is parsed, the library must decide how to represent each value in the Java world. The mapping is largely intuitive, but there are a few nuances that developers should be awaresses to avoid subtle bugs.

JSON type Typical Java representation Common Jackson annotation Common Gson nuance
String String – –
Number (no fraction) int, long, BigInteger (or double/BigDecimal for fractions) @JsonFormat(shape = JsonFormat.Shape.On top of that, class) for exact decimal handling Gson defaults to double for any number containing a decimal point
Boolean boolean – –
null Java null (or Optional. NUMBER) can be used for precise control Gson infers int/long for integral numbers; use JsonDeserializer if you need BigDecimal
Floating‑point number float, double, BigDecimal Same as above; @JsonDeserialize(using = BigDecimalDeserializer.empty() if you prefer) @JsonProperty can be marked required = false
Array List<T>, Set<T>, T[] `@JsonDeserialize(contentAs = MyItem.

Handling Nested Structures

Both Jackson and Gson can work through arbitrarily deep hierarchies without extra effort. The following compact example demonstrates reading a JSON object that contains a list of sub‑objects:

// Sample JSON (saved in nested.json):
// {
//   "id": 42,
//   "name": "Acme",
//   "tags": [
//     {"key": "region", "value": "US"},
//     {"key": "priority", "value": "high"}
//   ]
// }

class Tag {
    private String key;
    private String value;
    // getters & setters
}

class Container {
    private int id;
    private String name;
    private List tags;
    // getters & setters
}

// Jackson
ObjectMapper mapper = new ObjectMapper();
Container c = mapper.readValue(new File("nested.getTags().So out. json"), Container.println(c.class);
System.get(0).

// Gson
Gson gson = new Gson();
Container c2 = gson.out.getTags().fromJson(new FileReader("nested.Practically speaking, class);
System. json"), Container.In real terms, println(c2. get(0).

Notice that **no explicit type information** is required in the JSON; the libraries infer the shape from the target Java classes.

#### Error Handling and Robustness

Real‑world data is rarely perfect. Both libraries throw checked exceptions that you should catch:

* **Jackson** – `JsonParseException` (malformed JSON), `JsonMappingException` (type mismatch), `IOException` (I/O problems).
* **Gson** – `JsonSyntaxException` (covers both parse and mapping errors), `IOException`.

A defensive approach is to wrap the parsing logic in a try‑catch block and log a meaningful error message:

```java erotická
try {
    DataRecord record = mapper.readValue(new File("data.json"), DataRecord.class);
    // process record
} catch (JsonParseException e) {
    logger.error("Invalid JSON syntax in data.json", e);
} catch (IOException e) {
    logger.error("Unable to read data.json", e);
}

You can also configure the parsers to

You can also configure the parsers to meet domain‑specific needs that go beyond the default behavior of Jackson and Gson. Below are a few common scenarios where fine‑grained control is required, together with idiomatic ways to achieve them.

1. Custom Deserialization of Complex Types

When a JSON field represents a nested entity that contains its own collection, you may want to enforce validation rules or enrich the model after the raw JSON is parsed.

  • Jackson – implement a JsonDeserializer<T> and register it with the ObjectMapper. The deserializer receives the raw JSON string (or a JsonNode) and can call your own business logic before returning the fully constructed object.
public class TagDeserializer extends JsonDeserializer {
    @Override
    public Tag deserialize(JsonParser p, TypeType type, DeserializationContext ctx) throws IOException {
        JsonNode node = p.getCode().asText();          // e.g. "{\"key\":\"region\",\"value\":\"US\"}"
        String key = node.get("key").asText();
        String value = node.get("value").asText();
        return new Tag(key, value);
    }
}
ObjectMapper mapper = new ObjectMapper()
        .registerDeserializer(Tag.class, TagDeserializer.class);
  • Gson – use an JsonSerializable implementation or a custom JsonDeserializer. The latter gives you direct access to the JSON node hierarchy.
public class TagDeserializer implements JsonDeserializer {
    @Override
    public Tag deserialize(JsonParser p, TypeToken type, DeserializationContext ctx) throws JsonDeserializationException {
        JsonNode node = p.getCode();
        return new Tag(
                node.get("key").asText(),
                node.get("value").asText()
        );
    }
}
Gson gson = new Gson().setDeserializer(Tag.class, TagDeserializer.class);

2. Providing Default Values for Optional Fields

Both libraries support default values, but the placement matters. With Jackson you can declare them on the class, with Gson you can use defaultValue on the field or in the JsonObject.

// Jackson
public class User {
    private String id;                     // required
    private String email;
    public User() { id = 0; }               // implicit default for missing fields
    public User(String email) { this.email = email; }
}
ObjectMapper mapper = new ObjectMapper().setDefaultValue("N/A", String.class);
// Gson
public class User {
    private String id;
    private String email = "unknown";      // field‑level default
    public User(String email) { this.email = email; }
}
Gson gson = new Gson();   // automatically uses the defaults defined above

3. Handling Circular References

JSON itself cannot represent circular structures, but when you map a Java object to JSON you may inadvertently create cycles (e.g., a Node that references its parent). Both libraries can be instructed to break the cycle safely The details matter here..

  • Jackson – configure a JsonSerializer or use ObjectMapper’s readValue with strict mode disabled, which prevents infinite loops. A more explicit approach is to register a JsonNode‑based JsonSerializer that checks for already‑serialized references.
ObjectMapper mapper = new ObjectMapper()
        .setSerializationInvariant(false)   // allows circular structures during write
        .registerModule(new DefaultTypedValueModule()); // example of custom module
  • Gson – by default Gson does not generate circular references, but you can enforce this behavior with a JsonSerializer that tracks already‑seen objects.
public class NoCycleSerializer extends JsonSerializer {
    private final Set seen = new HashSet<>();

    @Override
    public String serialize(String value) throws JsonParseException {
        if (seen.Consider this: add(value);
        return value;
    }
}
Gson gson = new Gson(). Even so, contains(value)) {
            throw new IllegalStateException("Circular reference detected");
        }
        seen. setSerializer(NoCycleSerializer.

### 4. Enabling or Disabling `serializeNulls`  

When you need to preserve `null` values in the output (for example, to signal optional fields that may legit

      

      
      
Don't Stop

Straight from the Editor

Readers Also Checked

Readers Went Here Next

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