JSON in Java

Su Suriya Ravichandran Updated 18 Nov 2026
11 min read ·Lesson 275 of 306

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 valueExampleTypical 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)
Number4999, 4.8int, long, double, BigDecimal
Booleantrueboolean
Nullnullnull
LibraryPackageStrengths
Gsoncom.google.gsonSmall, simple API, no configuration needed
Jacksoncom.fasterxml.jackson / tools.jacksonVery fast, many modules, default in Spring Boot
Jakarta JSON-B / JSON-Pjakarta.json.bind / jakarta.jsonStandard 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: toJson turns objects into text and fromJson turns 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 List becomes a JSON array.
  • mentor is null, so Gson leaves it out by default. The next section shows how to include it.
  • A Gson instance is thread-safe and reusable. Create it once (for example as a static final field) instead of on every call.

Configure Gson With GsonBuilder

GsonBuilder changes how JSON is written: indentation, nulls, key names and character escaping.

Builder methodEffect
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 \u0026 and \u0027 so the JSON is safe to embed in HTML. The value is identical after parsing, but disableHtmlEscaping() makes the text readable.
  • LOWER_CASE_WITH_UNDERSCORES gives 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_code fills code through @SerializedName, and alternate lets the fee component also accept the key price.
  • Unknown keys such as rating are ignored, so an API can add fields without breaking your code.
  • Missing keys become null for objects and 0 or false for 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 {} after new TypeToken<...>() creates an anonymous subclass, which is how the generic type survives erasure. Type erasure is explained in the generics lessons.
  • With List.class only, every element becomes a map and every number a double (4999.0). Always pass a TypeToken for 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, getAsJsonArray and getAsInt move through the tree and convert values.
  • has checks for a key before reading it; get returns null for a missing key.
  • The REST lesson used this model to apply PATCH updates, 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 password is 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:

  • write and read use Gson's streaming JsonWriter and JsonReader, the same low-level API Gson uses internally.
  • nullSafe() wraps the adapter so JSON null becomes Java null without 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 parent JsonParseException) and answer with a clear error, such as 400 Bad Request in a servlet built with HttpServletResponse in Java.
  • Empty input does not throw: fromJson returns null. Check the result before using it, or a NullPointerException follows 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:

  1. Streaming input. fromJson(reader, typeToken) parses directly from the file reader into a List<Enrollment>, without loading the text into one big string first.
  2. Dates as real dates. The LocalDateAdapter turns "2026-11-02" into a LocalDate, so the program can compare dates with isAfter instead of comparing strings.
  3. 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.
  4. Nested output from records. Report contains a List and a TreeMap of CourseTotal records, and Gson writes the whole structure in one call. The TreeMap keeps the courses sorted, and generatedOn shows the day the program runs.
  5. Reusable configuration. One Gson instance 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.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about JSON in Java and get answers drawn from it.

Signed-in readers only.