JSON Handling in Java
Introduction
JSON is the dominant text format for APIs and config files. The JDK has no high-level JSON mapper in the standard library—projects add Gson or Jackson. This chapter uses Gson for clarity; production apps often choose Jackson for performance and ecosystem.
Tip
Format JSON for Reading
Paste messy JSON into JSON Formatter to inspect structure before coding parsers.
Prerequisites
- Classes, Collections
- File Handling
- Maven for dependency setup (or manual JAR for learning)
Gson Dependency (Maven)
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.11.0</version>
</dependency>Gradle users: see Gradle.
1) Object ↔ JSON String
import com.google.gson.Gson;
record Student(String name, int score) {}
public class JsonDemo {
public static void main(String[] args) {
Gson gson = new Gson();
Student student = new Student("Emma", 95);
String json = gson.toJson(student);
System.out.println(json);
Student parsed = gson.fromJson(json, Student.class);
System.out.println(parsed.name() + " -> " + parsed.score());
}
}2) Pretty Printing
import com.google.gson.GsonBuilder;
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String pretty = gson.toJson(student);
System.out.println(pretty);3) JSON Arrays and Collections
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.List;
Gson gson = new Gson();
String json = "[{\"name\":\"Emma\",\"score\":95},{\"name\":\"Liam\",\"score\":88}]";
Type listType = new TypeToken<List<Student>>() {}.getType();
List<Student> students = gson.fromJson(json, listType);4) Map and Dynamic JSON
import java.util.Map;
String json = "{\"name\":\"Ava\",\"score\":90}";
Map<?, ?> map = gson.fromJson(json, Map.class);
System.out.println(map.get("name"));For schema-less data, Map or JsonObject (Gson API) works; prefer typed classes when structure is known.
5) Read/Write JSON Files
import java.nio.file.Files;
import java.nio.file.Path;
Path path = Path.of("student.json");
Files.writeString(path, gson.toJson(student));
String fromFile = Files.readString(path);
Student loaded = gson.fromJson(fromFile, Student.class);Jackson (Awareness)
Jackson (ObjectMapper) is common in Spring Boot:
// ObjectMapper mapper = new ObjectMapper();
// String json = mapper.writeValueAsString(student);Choose Gson for learning simplicity; Jackson for large services.
Common Beginner Mistakes
Field Name Mismatch
JSON keys must match field names (or use @SerializedName in Gson).
Missing No-arg Constructor
Gson needs accessible constructor for non-record classes. Records work well with modern Gson.
Manual String Concatenation for JSON
Error-prone—use a library.
What’s Next
Build automation with Maven.
FAQ
Gson vs Jackson?
Gson simpler for tutorials; Jackson faster and standard in enterprise Spring stacks.
How to handle dates in JSON?
Configure type adapters or use ISO-8601 strings with java.time (Date and Time).
Validate JSON before parse?
Use formatter tool or schema validators in APIs (advanced).
Null fields?
Gson skips nulls by default in output depending on config—document API contracts.
Security?
Do not deserialize untrusted JSON into arbitrary types (gadget attacks)—use strict DTOs in production.