JSON in Java
JSON in Java means converting Java objects to JSON text (serialization) and JSON text back to Java objects (deserialization). JSON is the standard data format for REST APIs, configuration files and message queues, so almost every Java application reads or writes it. The JDK has no built-in JSON API, so you use a library such as Gson, Jackson or Jakarta JSON Binding.
This lesson uses Gson 2.14, the library already used in the servlet lessons, and covers objects, records, lists, maps, the tree model, custom field names, dates and error handling. It ends with a program that imports enrollments from a JSON file and writes a JSON report.
JSON Syntax and Java Types
| JSON value | Example | Typical Java type |
|---|---|---|
| Object | {"code":"java","lessons":306} | Class, record or Map<String, ?> |
| Array | ["oop","web"] | List<T> or array |
| String | "Java Programming" | String, LocalDate (with an adapter) |
| Number | 4999, 4.8 | int, long, double, BigDecimal |
| Boolean | true | boolean |
| Null | null | null |
| Library | Package | Strengths |
|---|---|---|
| Gson | com.google.gson | Small, simple API, no configuration needed |
| Jackson | com.fasterxml.jackson / tools.jackson | Very fast, many modules, default in Spring Boot |
| Jakarta JSON-B / JSON-P | jakarta.json.bind / jakarta.json | Standard APIs built into Jakarta EE servers |
How it works:
- JSON keys are always strings in double quotes. Java field or record component names map to those keys.
- All three libraries follow the same idea:
toJsonturns objects into text andfromJsonturns text into objects. Learning Gson makes the others easy to pick up.
Add Gson to Your Project
<!-- Maven: pom.xml -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.14.0</version>
</dependency>
// Gradle: build.gradle.kts
dependencies {
implementation("com.google.code.gson:gson:2.14.0")
}
How it works:
- In a web application this JAR is packaged into
WEB-INF/lib, as in the REST API in Java lesson. - To run the single-file examples below without a build tool, download the JAR and run
java -cp gson-2.14.0.jar ToJsonDemo.java.
Convert a Java Object to JSON With toJson
toJson reads an object's fields (or a record's components) and writes them as JSON.
import com.google.gson.Gson;
import java.util.List;
import java.util.Map;
public class ToJsonDemo {
record Student(String name, int age, boolean active, List<String> courses, String mentor) {}
public static void main(String[] args) {
Gson gson = new Gson();
Student student = new Student("Asha", 21, true, List.of("java", "go"), null);
System.out.println(gson.toJson(student));
System.out.println(gson.toJson(List.of(1, 2, 3)));
System.out.println(gson.toJson(Map.of("course", "java")));
System.out.println(gson.toJson("plain text"));
}
}
Output:
{"name":"Asha","age":21,"active":true,"courses":["java","go"]}
[1,2,3]
{"course":"java"}
"plain text"
How it works:
- The record's components become JSON keys in declaration order, and the
Listbecomes a JSON array. mentorisnull, so Gson leaves it out by default. The next section shows how to include it.- A
Gsoninstance is thread-safe and reusable. Create it once (for example as astatic finalfield) instead of on every call.
Configure Gson With GsonBuilder
GsonBuilder changes how JSON is written: indentation, nulls, key names and character escaping.
| Builder method | Effect |
|---|---|
setPrettyPrinting() | Multi-line output indented with two spaces |
serializeNulls() | Writes null fields instead of skipping them |
setFieldNamingPolicy(...) | Changes key style, such as fullName to full_name |
disableHtmlEscaping() | Writes &, ', <, >, = as normal characters |
registerTypeAdapter(...) | Custom conversion for a type (dates, money) |
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class GsonBuilderDemo {
record Profile(String fullName, String bio, String mentorName) {}
public static void main(String[] args) {
Profile profile = new Profile("Asha R", "Loves Java & Go's speed", null);
System.out.println(new Gson().toJson(profile));
Gson customGson = new GsonBuilder()
.setPrettyPrinting()
.serializeNulls()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.disableHtmlEscaping()
.create();
System.out.println(customGson.toJson(profile));
}
}
Output:
{"fullName":"Asha R","bio":"Loves Java \u0026 Go\u0027s speed"}
{
"full_name": "Asha R",
"bio": "Loves Java & Go's speed",
"mentor_name": null
}
How it works:
- By default Gson escapes
&and'as\u0026and\u0027so the JSON is safe to embed in HTML. The value is identical after parsing, butdisableHtmlEscaping()makes the text readable. LOWER_CASE_WITH_UNDERSCORESgives snake_case keys, a common style in public APIs.- Pretty printing helps for files and logs; keep the compact form for network responses.
Convert JSON to a Java Object With fromJson
fromJson creates an object from JSON text. @SerializedName maps a JSON key that differs from the Java name.
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
public class FromJsonDemo {
record Course(
@SerializedName("course_code") String code,
String title,
@SerializedName(value = "fee", alternate = {"price"}) int fee) {}
public static void main(String[] args) {
Gson gson = new Gson();
String apiJson = """
{"course_code":"java","title":"Java Programming","price":4999,"rating":4.8}""";
Course course = gson.fromJson(apiJson, Course.class);
System.out.println(course);
System.out.println("Fee with GST: " + Math.round(course.fee() * 1.18));
Course partial = gson.fromJson("{\"title\":\"Go Language\"}", Course.class);
System.out.println(partial);
System.out.println(gson.toJson(course));
}
}
Output:
Course[code=java, title=Java Programming, fee=4999]
Fee with GST: 5899
Course[code=null, title=Go Language, fee=0]
{"course_code":"java","title":"Java Programming","fee":4999}
How it works:
course_codefillscodethrough@SerializedName, andalternatelets thefeecomponent also accept the keyprice.- Unknown keys such as
ratingare ignored, so an API can add fields without breaking your code. - Missing keys become
nullfor objects and0orfalsefor primitives. Always validate required fields after parsing. - When writing JSON, Gson uses the main name (
fee), never the alternate.
Read JSON Lists and Maps With TypeToken
Java erases generic types at runtime, so List<Course>.class does not exist. A TypeToken keeps the full generic type for Gson.
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.util.List;
import java.util.Map;
public class TypeTokenDemo {
record CourseFee(String code, int fee) {}
public static void main(String[] args) {
Gson gson = new Gson();
String json = """
[{"code":"java","fee":4999},{"code":"go","fee":2999}]""";
List<CourseFee> fees = gson.fromJson(json, new TypeToken<List<CourseFee>>() {});
System.out.println(fees.get(1).code() + " costs " + fees.get(1).fee());
Map<String, Integer> seats = gson.fromJson("{\"java\":12,\"go\":5}",
new TypeToken<Map<String, Integer>>() {});
System.out.println("Total seats: " + (seats.get("java") + seats.get("go")));
// Without a TypeToken Gson has no element type to use
List<?> raw = gson.fromJson(json, List.class);
System.out.println(raw.get(0) + " -> " + raw.get(0).getClass().getSimpleName());
}
}
Output:
go costs 2999
Total seats: 17
{code=java, fee=4999.0} -> LinkedTreeMap
How it works:
- The
{}afternew TypeToken<...>()creates an anonymous subclass, which is how the generic type survives erasure. Type erasure is explained in the generics lessons. - With
List.classonly, every element becomes a map and every number adouble(4999.0). Always pass aTypeTokenfor generic collections.
Work With the JSON Tree Model
When you need only a few values, or the structure varies, parse into a tree of JsonObject, JsonArray and JsonPrimitive instead of defining classes.
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class TreeModelDemo {
public static void main(String[] args) {
String response = """
{"course":{"code":"java","modules":[{"name":"Basics","lessons":28},{"name":"OOP","lessons":23}]},"published":true}""";
JsonObject root = JsonParser.parseString(response).getAsJsonObject();
JsonObject course = root.getAsJsonObject("course");
int totalLessons = 0;
for (JsonElement module : course.getAsJsonArray("modules")) {
totalLessons += module.getAsJsonObject().get("lessons").getAsInt();
}
System.out.println(course.get("code").getAsString() + " has " + totalLessons + " lessons");
System.out.println("Published? " + root.get("published").getAsBoolean());
System.out.println("Has price? " + course.has("price"));
// Build new JSON by hand
JsonObject summary = new JsonObject();
summary.addProperty("code", "java");
summary.addProperty("totalLessons", totalLessons);
JsonArray tags = new JsonArray();
tags.add("oop");
tags.add("web");
summary.add("tags", tags);
System.out.println(summary);
}
}
Output:
java has 51 lessons
Published? true
Has price? false
{"code":"java","totalLessons":51,"tags":["oop","web"]}
How it works:
getAsJsonObject,getAsJsonArrayandgetAsIntmove through the tree and convert values.haschecks for a key before reading it;getreturnsnullfor a missing key.- The REST lesson used this model to apply
PATCHupdates, where only some fields are present.
Exclude Fields With transient
Fields marked transient are skipped in both directions. Use it for passwords, caches and other data that must never appear in JSON.
import com.google.gson.Gson;
public class TransientDemo {
static class Account {
String username = "asha";
transient String password = "s3cret"; // never written, never read
String role = "student";
}
public static void main(String[] args) {
Gson gson = new Gson();
System.out.println(gson.toJson(new Account()));
Account loaded = gson.fromJson("{\"username\":\"ravi\",\"password\":\"hacked\"}", Account.class);
System.out.println(loaded.username + " / " + loaded.password + " / " + loaded.role);
}
}
Output:
{"username":"asha","role":"student"}
ravi / s3cret / student
How it works:
- The password never reaches the JSON output.
- When reading, Gson creates the object with its no-argument constructor, so field initializers run first. The incoming
passwordis ignored and keeps its default, which proves clients cannot set it. - Records cannot have instance fields beyond their components. For records, leave sensitive data out of the record or use a separate response record.
Convert Dates With a Custom TypeAdapter
Gson has no built-in support for java.time types, and on modern JDKs its reflection fallback cannot read their private fields. Register a TypeAdapter that writes ISO-8601 strings.
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.time.LocalDate;
public class DateAdapterDemo {
static class LocalDateAdapter extends TypeAdapter<LocalDate> {
@Override
public void write(JsonWriter out, LocalDate date) throws IOException {
out.value(date.toString()); // "2026-12-07"
}
@Override
public LocalDate read(JsonReader in) throws IOException {
return LocalDate.parse(in.nextString());
}
}
record Batch(String course, LocalDate startDate) {}
public static void main(String[] args) {
Gson gson = new GsonBuilder()
.registerTypeAdapter(LocalDate.class, new LocalDateAdapter().nullSafe())
.create();
System.out.println(gson.toJson(new Batch("java", LocalDate.of(2026, 12, 7))));
Batch next = gson.fromJson("{\"course\":\"go\",\"startDate\":\"2027-01-11\"}", Batch.class);
System.out.println(next.course() + " starts on a " + next.startDate().getDayOfWeek());
Batch unscheduled = gson.fromJson("{\"course\":\"python\",\"startDate\":null}", Batch.class);
System.out.println(unscheduled);
}
}
Output:
{"course":"java","startDate":"2026-12-07"}
go starts on a MONDAY
Batch[course=python, startDate=null]
How it works:
writeandreaduse Gson's streamingJsonWriterandJsonReader, the same low-level API Gson uses internally.nullSafe()wraps the adapter so JSONnullbecomes Javanullwithout extra checks.- ISO-8601 dates sort correctly as text and are understood by JavaScript and almost every other language.
Handle Invalid JSON Safely
Data from users and other systems may be broken. Gson throws JsonSyntaxException for malformed JSON and for values of the wrong type.
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
public class InvalidJsonDemo {
record CourseInfo(String code, int lessons) {}
public static void main(String[] args) {
Gson gson = new Gson();
String[] inputs = {
"{\"code\":\"java\",\"lessons\":306}", // valid
"{\"code\":\"java\",\"lessons\":306", // missing closing brace
"{\"code\":\"java\",\"lessons\":\"many\"}", // text where a number is expected
"" // empty input
};
for (String input : inputs) {
try {
CourseInfo info = gson.fromJson(input, CourseInfo.class);
System.out.println("OK: " + info);
} catch (JsonSyntaxException e) {
System.out.println("Invalid: " + e.getClass().getSimpleName());
}
}
}
}
Output:
OK: CourseInfo[code=java, lessons=306]
Invalid: JsonSyntaxException
Invalid: JsonSyntaxException
OK: null
How it works:
- Catch
JsonSyntaxException(or its parentJsonParseException) and answer with a clear error, such as400 Bad Requestin a servlet built with HttpServletResponse in Java. - Empty input does not throw:
fromJsonreturnsnull. Check the result before using it, or aNullPointerExceptionfollows later.
Real-World Example: JSON in Java for an Enrollment Import Report
An admin exports enrollments as enrollments.json. The program reads the file, rejects invalid rows, totals students and revenue per course, and writes report.json.
[
{"student": "Asha", "course": "java", "paidInr": 4999, "enrolledOn": "2026-11-02"},
{"student": "Ravi", "course": "go", "paidInr": 2999, "enrolledOn": "2026-11-05"},
{"student": "Meena", "course": "java", "paidInr": 3999, "enrolledOn": "2026-11-09"},
{"student": "", "course": "python", "paidInr": 3999, "enrolledOn": "2026-11-10"},
{"student": "Karthik", "course": "java", "paidInr": -10, "enrolledOn": "2026-11-12"}
]
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class EnrollmentReport {
record Enrollment(String student, String course, int paidInr, LocalDate enrolledOn) {}
record CourseTotal(int students, int revenueInr, LocalDate latestEnrollment) {}
record Report(LocalDate generatedOn, int accepted, List<String> rejected,
Map<String, CourseTotal> courses) {}
static class LocalDateAdapter extends TypeAdapter<LocalDate> {
@Override public void write(JsonWriter out, LocalDate date) throws IOException { out.value(date.toString()); }
@Override public LocalDate read(JsonReader in) throws IOException { return LocalDate.parse(in.nextString()); }
}
public static void main(String[] args) throws IOException {
Gson gson = new GsonBuilder()
.registerTypeAdapter(LocalDate.class, new LocalDateAdapter().nullSafe())
.setPrettyPrinting()
.disableHtmlEscaping()
.create();
// 1. Read the whole file straight into typed records
List<Enrollment> enrollments;
try (Reader reader = Files.newBufferedReader(Path.of("enrollments.json"))) {
enrollments = gson.fromJson(reader, new TypeToken<List<Enrollment>>() {});
}
// 2. Validate each row and total the valid ones per course
List<String> rejected = new ArrayList<>();
Map<String, CourseTotal> totals = new TreeMap<>(); // sorted by course code
for (Enrollment row : enrollments) {
if (row.student() == null || row.student().isBlank()) {
rejected.add(row.course() + ": student name missing");
continue;
}
if (row.paidInr() < 0) {
rejected.add(row.student() + ": negative payment");
continue;
}
totals.merge(row.course(), new CourseTotal(1, row.paidInr(), row.enrolledOn()),
(old, add) -> new CourseTotal(
old.students() + add.students(),
old.revenueInr() + add.revenueInr(),
old.latestEnrollment().isAfter(add.latestEnrollment())
? old.latestEnrollment() : add.latestEnrollment()));
}
// 3. Write the report as pretty JSON
Report report = new Report(LocalDate.now(), enrollments.size() - rejected.size(), rejected, totals);
try (Writer writer = Files.newBufferedWriter(Path.of("report.json"))) {
gson.toJson(report, writer);
}
System.out.println(Files.readString(Path.of("report.json")));
}
}
java -cp gson-2.14.0.jar EnrollmentReport.java
Output:
{
"generatedOn": "2026-11-18",
"accepted": 3,
"rejected": [
"python: student name missing",
"Karthik: negative payment"
],
"courses": {
"go": {
"students": 1,
"revenueInr": 2999,
"latestEnrollment": "2026-11-05"
},
"java": {
"students": 2,
"revenueInr": 8998,
"latestEnrollment": "2026-11-09"
}
}
}
How it works:
- Streaming input.
fromJson(reader, typeToken)parses directly from the file reader into aList<Enrollment>, without loading the text into one big string first. - Dates as real dates. The
LocalDateAdapterturns"2026-11-02"into aLocalDate, so the program can compare dates withisAfterinstead of comparing strings. - Validation after parsing. JSON syntax can be perfect while the data is still wrong. The blank student name and the negative payment are rejected with a reason each, and only valid rows reach the totals.
- Nested output from records.
Reportcontains aListand aTreeMapofCourseTotalrecords, and Gson writes the whole structure in one call. TheTreeMapkeeps the courses sorted, andgeneratedOnshows the day the program runs. - Reusable configuration. One
Gsoninstance carries the adapter, pretty printing and readable characters for both reading and writing. The same instance could serve a servlet API or a client built with Java HttpClient.