Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 119 ยท Data Formats

JSON with Jackson

Convert Java objects to JSON and back with Jackson's ObjectMapper - records, POJOs, lists and maps, TypeReference, pretty printing, java.time dates and errors.

JSON is the language that web services, configuration files, message queues and browsers use to exchange data. In Java, the library almost everyone uses to read and write it is Jackson. Spring Boot uses it for every REST endpoint, and many other frameworks depend on it too.

This lesson covers the everyday 90%: turning records and classes into JSON and back with ObjectMapper, handling lists and maps, pretty printing, dates from java.time, and understanding the errors Jackson throws. The examples run Jackson 2.22 with the Java Time module. Advanced Jackson then covers annotations, the tree model, polymorphism and custom serializers.

JSON in two minutes

A JSON document is one value, and a value is one of six things:

JSON type Example Typical Java type
object {"name": "Ana", "age": 31} a record or class, or Map<String, Object>
array [1, 2, 3] List<T> or an array
string "hello" String, enums, dates
number 42, -3.5, 1e9 int, long, double, BigDecimal
boolean true, false boolean
null null null

The rules are strict: keys and strings use double quotes, there are no comments and no trailing commas, and numbers have no leading zeros or + signs. JSON has no date type, so dates travel as strings (preferably ISO 8601 such as "2025-03-01") or numbers.

Adding Jackson to a project

Jackson is split into small modules. jackson-databind is the one you add; it pulls in jackson-core (the streaming parser) and jackson-annotations. Support for java.time lives in a separate module. In Maven (read-only; see Maven in Depth):

XML
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.22.3</version>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.datatype</groupId>
  <artifactId>jackson-datatype-jsr310</artifactId>
  <version>2.22.3</version>
</dependency>

In real projects, a Jackson BOM (bill of materials) or Spring Boot's dependency management keeps all module versions in step. Mixing versions of Jackson modules is a classic source of NoSuchMethodError.

ObjectMapper: objects to JSON and back

ObjectMapper is the central class. Two methods do most of the work:

  • writeValueAsString(object) serializes: Java object โ†’ JSON text.
  • readValue(json, Type.class) deserializes: JSON text โ†’ Java object.
Java Your first round trip

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice what you did not write: no parsing loop, no string building. Jackson looked at the record's components, used their names as JSON keys and their values as JSON values, and handled the nested Address and the List automatically. When reading, it called the record's canonical constructor. The pretty printer's style, with a space before each colon, is Jackson's default.

Create one ObjectMapper and reuse it. It is expensive to build (it caches what it learns about each class) but thread-safe once configured, so a single static final instance or one injected bean is the norm. Creating a new mapper per request is a common performance bug.

How Jackson finds properties

Jackson calls the fields it reads and writes properties, and it discovers them by convention:

  • Records: every component is a property. Deserialization uses the canonical constructor.
  • Classes (POJOs): public getters (getName(), and isActive() for boolean) define what is written; setters or public fields define what can be read. Deserialization needs a no-argument constructor (it may be private) unless you use annotations covered in the next lesson.
  • Private fields without getters are invisible. A class with no visible properties at all fails with "No serializer found for class ...".

The getter rule has a surprising side effect: any method that looks like a getter becomes a property, even a computed one.

Java POJOs: getters decide what is written

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

isExpensive() added an "expensive" key, and internalNote was skipped. Then reading the JSON we had just written failed, because Jackson found a key it had no way to set. By default, Jackson rejects unknown properties, which catches typos and API mismatches early but also breaks clients when a server adds a field. You will learn to control both behaviors (@JsonIgnore, @JsonIgnoreProperties(ignoreUnknown = true) and FAIL_ON_UNKNOWN_PROPERTIES) in Advanced Jackson.

Records avoid most of these surprises: what you see in the header is exactly what gets written and read. Prefer them for data you send and receive.

Lists, maps and generic types

Writing collections just works: a List becomes a JSON array and a Map with string keys becomes a JSON object. Reading them needs one extra step, because of type erasure: List<Customer>.class doesn't exist, and readValue(json, List.class) can't know what the elements should be. It gives you a List of LinkedHashMaps.

The fix is a TypeReference, an anonymous subclass that captures the full generic type:

Java
List<Customer> customers = mapper.readValue(json, new TypeReference<List<Customer>>() {});

When you don't have a class for the data at all, you can read into Map<String, Object>. Jackson then picks Java types for you: String, Integer (or Long for big values), Double, Boolean, ArrayList for arrays, LinkedHashMap for objects, and null.

Java Generic types and untyped maps

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The untyped map works, but every access needs casts like (Map<String, Object>) data.get("meta"). For JSON whose shape you don't know in advance, Jackson's tree model (JsonNode) is far nicer; it is covered in the next lesson.

Note that 9007199254740993 arrived intact as a Long. JavaScript would have rounded it, because JavaScript numbers are doubles. When an API sends 64-bit IDs to browsers, it is common to send them as strings.

Numbers and money

By default, JSON decimals are read as double when the target is Object or double, which brings the usual rounding problems (0.1 + 0.2 is 0.30000000000000004). For prices, use BigDecimal in your records; Jackson reads and writes them exactly, so "price": 19.90 stays 19.90. When reading untyped data, mapper.enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS) makes Jackson use BigDecimal for every decimal. See BigInteger and BigDecimal.

When reading fails

Jackson's exceptions all extend JsonProcessingException (itself an IOException, which is why the examples declare throws Exception). The ones you will meet most:

Exception Cause
JsonParseException, JsonEOFException The text is not valid JSON: a missing quote, comma or brace.
UnrecognizedPropertyException A key that your class has no property for.
InvalidFormatException A value of the wrong kind, such as "five" for an int, or an unknown enum constant.
MismatchedInputException The structure doesn't fit, such as an array where an object was expected.
InvalidDefinitionException A problem with your class, not the data: no constructor Jackson can use, or an unsupported type.

The messages are detailed: they include the line and column and a "reference chain" showing where in the object graph the problem was.

Java What Jackson says when input is bad

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The last two lines deserve a second look, because they succeed:

  • Missing properties are not an error. A7 has no qty or size, so Jackson passes the defaults, 0 and null. If a field is required, validate after reading (or use Bean Validation in Spring, see Validation and Error Handling).
  • Jackson coerces simple types. The string "3" became the number 3. That leniency is convenient, but can hide client bugs. Jackson's coercion settings can turn it off.

Never show these raw messages to end users of a public API: they reveal class names. Log them, and return a short, friendly error instead.

Dates and times with JavaTimeModule

java.time types such as LocalDate and Instant are not supported by plain databind. Without help, Jackson 2 refuses them with an InvalidDefinitionException telling you to add the jackson-datatype-jsr310 module. Register JavaTimeModule, and decide on the format:

  • With the default WRITE_DATES_AS_TIMESTAMPS enabled, a LocalDate becomes an array like [2025,3,1] and an Instant becomes seconds since 1970 as a decimal number. Compact, but unreadable and unusual.
  • With it disabled, you get ISO 8601 strings: "2025-03-01" and "2025-03-01T10:00:00Z". This is what almost every API wants, and what Spring Boot configures by default.

The modern way to configure a mapper is the JsonMapper.builder(), which collects modules and features before creating an immutable-style setup:

Java java.time with and without the module

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The ISO version round-trips perfectly. A few related points:

  • Duration has its own switch, WRITE_DURATIONS_AS_TIMESTAMPS; disable it too if you want "PT1H30M" instead of 5400.000000000.
  • LocalDateTime has no time zone. For moments in time (when an order was placed), prefer Instant or OffsetDateTime so the JSON carries the offset. See Dates and Times.
  • Optional fields need yet another module, jackson-datatype-jdk8 (not available on our server). Most teams avoid Optional in data classes anyway and use null plus validation.
  • mapper.findAndRegisterModules() registers every Jackson module found on the classpath. It's handy, but explicit addModule calls make it obvious what your mapper supports.

Files, streams and a classic trap

readValue and writeValue also accept File, Path-based streams, InputStream, Reader, OutputStream and Writer. Streaming straight to and from I/O avoids building a giant String in memory.

There is one trap: by default, writeValue(outputStream, value) closes the stream when it is done (the JsonGenerator.Feature.AUTO_CLOSE_TARGET setting). For files that's what you want. For System.out, it means everything you print afterwards disappears.

Java Writing JSON to a file, and to System.out

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Delete the .without(...) call and run again: the JSON appears, but the last line never does, because System.out was closed. In application code you rarely write to System.out, but the same thing happens with any stream you meant to keep using, such as a socket or an HTTP response you still want to write to.

A note on Jackson 3

Jackson 3.0 was released in late 2025, and new frameworks (Spring Boot 4, for example) are moving to it. Your knowledge transfers almost entirely, but code needs a few changes:

  • New package and Maven group names: com.fasterxml.jackson.databind becomes tools.jackson.databind, and the group ID becomes tools.jackson.core. The annotations stay in com.fasterxml.jackson.annotation, so annotated classes mostly don't change.
  • java.time support is built in, and dates are written as ISO strings by default. No JavaTimeModule needed.
  • Mappers are immutable and created with builders such as JsonMapper.builder()...build(); changing settings later uses mapper.rebuild().
  • Exceptions are unchecked: JacksonException extends RuntimeException, so no more throws JsonProcessingException everywhere.
  • Jackson 3 requires Java 17 or newer. Jackson 2.x remains maintained, and both can live in one application because the packages differ.

Using JsonMapper.builder() today, as in the date example, makes a later migration easier.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does mapper.writeValueAsString(new Point(3, 4)) print for record Point(int x, int y)?

    Each record component becomes a JSON property with its name as the key. Jackson's compact output has no spaces.
  2. 2. You call mapper.readValue(json, List.class) on an array of customer objects. What are the elements?

    Because of type erasure, Jackson doesn't know the element type, so it uses maps. Pass a TypeReference such as new TypeReference<List<Customer>>() {} instead.
  3. 3. JSON {"id": "A7"} is read into record Order(String id, int qty, Size size). What happens?

    Jackson doesn't treat missing properties as errors by default. It passes default values to the constructor, so validate required fields yourself.
  4. 4. With JavaTimeModule registered and WRITE_DATES_AS_TIMESTAMPS disabled, how is LocalDate.of(2025, 3, 1) written?

    Disabling timestamps switches java.time types to ISO 8601 strings, the format most APIs expect.
  5. 5. Why should an application create one ObjectMapper and share it?

    The mapper caches serializers per class. Reusing a single configured instance is both safe and much faster than creating one per call.

Summary

  • Jackson's ObjectMapper converts between Java objects and JSON: writeValueAsString to serialize, readValue to deserialize. Build it once and share it.
  • Records map naturally (components โ‡„ properties). For classes, getters define what is written and setters/fields what is read; a no-arg constructor is needed.
  • Use TypeReference to read generic types like List<Item>; untyped reads give LinkedHashMap, ArrayList, Integer, Long, Double.
  • Use writerWithDefaultPrettyPrinter() for readable output and BigDecimal for money.
  • Unknown properties fail by default; missing properties silently become defaults; simple types are coerced.
  • Register JavaTimeModule and disable WRITE_DATES_AS_TIMESTAMPS to get ISO 8601 dates.
  • writeValue(stream, ...) closes the stream unless you turn off AUTO_CLOSE_TARGET.
  • Jackson 3 moves to tools.jackson.* packages, builds in java.time support and uses unchecked exceptions.

Next: Advanced Jackson shows how to rename, hide and format properties with annotations, navigate JSON as a tree and handle polymorphic types.