Skip to main content

Jackson ObjectMapper and JsonMapper (Jackson 2 and 3): Complete Guide with Examples

Learn Jackson’s ObjectMapper and Jackson 3’s JsonMapper from scratch: read and write JSON, configure the mapper once, handle dates and exceptions, and see exactly what changes between Jackson 2.23.0 and 3.3.0, with every example executed on both versions.

Every Java service that talks JSON needs one object that turns Java objects into JSON text and back again. In Jackson that object is the ObjectMapper — and in Jackson 3 it is built as a JsonMapper. This guide takes you from “I have never used it” to “I can configure it for production”, and every example is run on Jackson 2 and Jackson 3 in the same JVM, so you see exactly where the two differ instead of taking a migration guide’s word for it.
Verified versions. Jackson 3.3.0 (tools.jackson.core:jackson-databind) and Jackson 2.23.0 (com.fasterxml.jackson.core:jackson-databind), with jackson-annotations 2.23 shared by both, on Temurin JDK 25.0.5+8 and Maven 3.9.11. Both releases appeared on Maven Central on 8 November 2026 (that is the upload time in the repository directory listing; I could not find a project announcement for either, so I do not claim a release-note date or support status for 3.3).

Runnable code: every example is a small program in the objectmapper-jsonmapper module of the jackson3-by-example repository, and every console block below is copied from a file in its output folder. ./scripts/run-all.sh regenerates all of it.

What does an ObjectMapper actually do?

Your program holds data in Java objects. The outside world — a REST API, a config file, a message queue — holds the same data as JSON text. The mapper is the translator between the two, in both directions: serialising (object to JSON) and deserialising (JSON to object).
Java object Article(1, “Jackson…”) JSON text {“articleId”:1,…} The mapper Jackson 2: ObjectMapper · Jackson 3: JsonMapper generator writes tokens parser reads tokens writeValue… to JSON readValue… to object You only ever call the mapper. The generator and parser are inside it. Both directions go through the same configured object, which is why you build it once.
The diagram shows the one thing to hold on to: the mapper sits in the middle and every conversion, in either direction, goes through it. Inside it a generator writes JSON tokens and a parser reads them, but you almost never touch those directly. Because the mapper carries all your settings (date formats, null handling, naming style), the usual rule follows from the picture: build one, configure it once, share it everywhere. Later sections cash that rule in with real numbers. A word on names, because they confuse everyone at first. In Jackson 2 the class is com.fasterxml.jackson.databind.ObjectMapper and you create it with new ObjectMapper(). In Jackson 3 the package is tools.jackson.databind, the concrete class you build is tools.jackson.databind.json.JsonMapper, and ObjectMapper still exists as its parent class. So “ObjectMapper” is the concept in both versions, and “JsonMapper” is the Jackson 3 way of creating one. Three facts to keep in mind before any code:
  • It is thread-safe once configured. Create one instance and share it across the application; recreating it per request is expensive (measured below).
  • It is highly configurable. Date formats, null handling and unknown-property behaviour are controlled by feature flags.
  • It is extensible. Custom serialisers, deserialisers and modules let you handle types Jackson does not know about.
Going deeper: parser, generator and what “databind” means

Jackson is three layers. jackson-core is the streaming layer (parser and generator, no Java objects at all). jackson-annotations holds annotations such as @JsonProperty. jackson-databind sits on top and does the object mapping, which is the part this article is about. If you need to process a file too big for memory you drop down to the streaming layer; that is covered in Jackson Streaming API and JsonNode.

Add Jackson to your project

One dependency is enough; it pulls in the core and annotations libraries for you. This is the dependency block of the companion module’s pom.xml, which deliberately lists both majors so the examples can compare them (the Jackson 2 version comes from its BOM, and the jsr310 line exists only for the Jackson 2 date demo):
<dependencies>
  <dependency>
    <groupId>tools.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>${jackson3.version}</version>
  </dependency>
  <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
  </dependency>
  <dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
  </dependency>
</dependencies>
For Gradle, the Jackson 3 line is implementation 'tools.jackson.core:jackson-databind:3.3.0'; it is shown as a block in the module README. In your own project you want only one of the two databind dependencies above, not both.
Same artifact name, different group. Jackson 3 moved to tools.jackson.core, so the Jackson 2 and Jackson 3 jars never collide. The one exception is annotations: jackson-annotations stayed at com.fasterxml.jackson.core, and Maven resolved it to 2.23 when I asked for Jackson 3.3.0. That is why @JsonInclude and friends keep their com.fasterxml.jackson.annotation imports on Jackson 3, and why annotated classes work with either mapper.
Going deeper: the BOM and Spring Boot

Import tools.jackson:jackson-bom to keep every Jackson 3 module on one version, and com.fasterxml.jackson:jackson-bom for Jackson 2 (the module above imports the second). Spring Boot 4 uses Jackson 3 by default, so if you are on Boot 4 you meet JsonMapper first and the Jackson 2 ObjectMapper only through older libraries; the upgrade steps are in the Jackson 2 to 3 migration guide.

Your first round trip, in both versions

The class being converted is a plain Java bean with no Jackson annotations at all — the file is Article.java. Because it carries no annotations, the same class goes through both mappers untouched. Here is the whole write-and-read from P01TwoMappersSideBySide.java:
Article article = new Article(1L, "Jackson Deep Dive", List.of("java", "json"));

// ---- Jackson 2: package com.fasterxml.jackson.databind ----
com.fasterxml.jackson.databind.ObjectMapper m2 = new com.fasterxml.jackson.databind.ObjectMapper();
String json2 = m2.writeValueAsString(article);

// ---- Jackson 3: package tools.jackson.databind.json ----
tools.jackson.databind.json.JsonMapper m3 = tools.jackson.databind.json.JsonMapper.builder().build();
String json3 = m3.writeValueAsString(article);

System.out.println("Jackson 2 " + m2.version() + " -> " + json2);
System.out.println("Jackson 3 " + m3.version() + " -> " + json3);
System.out.println("identical JSON: " + json2.equals(json3));
System.out.println();

// Reading back is the same call in both.
Article back2 = m2.readValue(json2, Article.class);
Article back3 = m3.readValue(json3, Article.class);
And the real output, copied from P01TwoMappersSideBySide.txt:
Jackson 2 2.23.0 -> {"articleId":1,"title":"Jackson Deep Dive","tags":["java","json"],"subtitle":null}
Jackson 3 3.3.0 -> {"articleId":1,"subtitle":null,"tags":["java","json"],"title":"Jackson Deep Dive"}
identical JSON: false

Jackson 2 read title: Jackson Deep Dive
Jackson 3 read title: Jackson Deep Dive
Read that third line twice. The two mappers produced different JSON for the same object: Jackson 2 followed the order of the fields in the class, Jackson 3 sorted the property names alphabetically. Both are valid JSON and both read back fine, but a test that compares JSON strings would fail after an upgrade. This is a changed default, not a bug, and the configuration section shows how to flip it.
Two things that look like bugs and are not. The "subtitle":null is written because neither version skips nulls by default. And JsonMapper.builder().build() is the Jackson 3 form you will use as soon as you need any setting; a bare new JsonMapper() also compiles because the constructor is public (checked with javap), but it gives you no way to configure anything.
Going deeper: how the code works, and the class hierarchy

How it works. The first time the mapper meets a type it inspects the getters and fields, builds an internal model of the class, and caches it; later calls reuse that model. writeValueAsString() then writes each property to an in-memory buffer and returns the finished string, and readValue() tokenises the JSON and maps each token to the matching property using the cached model. This is the standard explanation of the design; the caching is also my working explanation for the Jackson 2 behaviour shown in the configuration section, though I did not confirm that in the source.

Hierarchy. The same program pretty-prints with writerWithDefaultPrettyPrinter() and prints the real class names, confirming that JsonMapper is a subclass of tools.jackson.databind.ObjectMapper and that the annotation package is shared. See P01 and its output.

Every way in and out: strings, bytes, files and streams

Real code rarely starts from a string literal. You read a request body as bytes, a config from a file, a response from a stream. The mapper has an overload for each, and the call shape is always the same: source (or target) first, type second.
You have…Read withWrite with
a StringreadValue(json, Article.class)writeValueAsString(obj)
byte[]readValue(bytes, Article.class)writeValueAsBytes(obj)
a File or PathreadValue(file, Article.class)writeValue(file, obj)
an InputStream / OutputStreamreadValue(in, Article.class)writeValue(out, obj)
a Reader / WriterreadValue(reader, Article.class)writeValue(writer, obj)
Here are the read calls from P03ReadWriteCookbook.java and what they printed (the first four output lines are the write side, which is in the same file):
System.out.println("read String      : " + mapper.readValue(asString, Article.class).getTitle());
System.out.println("read byte[]      : " + mapper.readValue(asBytes, Article.class).getTitle());
System.out.println("read File        : " + mapper.readValue(file.toFile(), Article.class).getTitle());
System.out.println("read Path        : " + mapper.readValue(file, Article.class).getTitle());
System.out.println("read InputStream : "
        + mapper.readValue(new ByteArrayInputStream(asBytes), Article.class).getTitle());
System.out.println("read Reader      : "
        + mapper.readValue(new StringReader(asString), Article.class).getTitle());
Source: P03ReadWriteCookbook.java (excerpt)
writeValueAsString : {"articleId":1,"subtitle":null,"tags":["java","json"],"title":"Jackson Deep Dive"}
writeValueAsBytes  : 82 bytes
writeValue(Path)   : {"articleId":1,"subtitle":null,"tags":["java","json"],"title":"Jackson Deep Dive"}
writeValue(Stream) : 82 bytes

read String      : Jackson Deep Dive
read byte[]      : Jackson Deep Dive
read File        : Jackson Deep Dive
read Path        : Jackson Deep Dive
read InputStream : Jackson Deep Dive
read Reader      : Jackson Deep Dive
Captured in output/P03ReadWriteCookbook.txt (excerpt)
A removed overload: readValue(URL, ...). The first version of this article showed mapper.readValue(new URL(...), Article.class). That works on Jackson 2 and does not compile on Jackson 3: the overload is gone. The program checks it by reflection, and the compiler’s own message is in the transcript (see the source and compiler output):

Broken2ReadValueUrl.java:7: error: no suitable method found for readValue(URL,Class<Object>)

To read from a URL, open the stream yourself with URI.create(...).toURL().openStream() (or your HTTP client) and pass the InputStream. The reflection check printed:
Jackson 2 readValue(URL, Class) exists : true
Jackson 3 readValue(URL, Class) exists : false
Jackson 3 readTree(URL) exists         : false
Captured in output/P03ReadWriteCookbook.txt (excerpt)
Going deeper: encoding, trees and reusable readers

Byte-based overloads (byte[], InputStream, File) detect or assume UTF-8, which is what JSON requires; the program round-trips five Devanagari characters through byte[] to prove it (last line of the output file). If you do not know the shape of the JSON in advance, readTree() gives you a JsonNode tree to navigate, and convertValue() converts between a bean and a Map without writing JSON at all — both are exercised in P03. When you read the same type thousands of times, mapper.readerFor(Article.class) gives a cheap, thread-safe, pre-typed reader.

Lists and maps: why TypeReference exists

Java forgets generic types at runtime. List<Article> and List<String> are the same class once the program is running, so passing List.class tells Jackson “a list” but not “a list of what”. TypeReference is a tiny trick (an anonymous subclass) that makes the compiler remember the full type for Jackson. From P03:
String array = "[{\"articleId\":1,\"title\":\"First\"},{\"articleId\":2,\"title\":\"Second\"}]";
List<Article> list = mapper.readValue(array, new TypeReference<List<Article>>() { });
System.out.println("List<Article> size   : " + list.size() + ", element class: " + list.get(0).getClass().getSimpleName());
List<?> raw = mapper.readValue(array, List.class);
Source: P03ReadWriteCookbook.java (excerpt)
List<Article> size   : 2, element class: Article
List.class element   : java.util.LinkedHashMap
Captured in output/P03ReadWriteCookbook.txt (excerpt)
The second line is the trap. readValue(json, List.class) does not fail: it quietly returns a list of LinkedHashMap. The error arrives later, as a ClassCastException the first time you treat an element as an Article, usually far from the real cause. In Jackson 3 the import is tools.jackson.core.type.TypeReference.
Going deeper: maps, generic wrappers and JavaType

The same pattern handles Map<String, Article> and generic wrappers such as a paginated Page<Article>: put the full type in the anonymous subclass. For types built at runtime, mapper.getTypeFactory() constructs a JavaType instead. The prompt section near the end of this article generates all four common shapes for your own classes.

Configure it once: why Jackson 3 mappers are immutable

In Jackson 2 you could call mapper.setSerializationInclusion(...), mapper.configure(...) or mapper.registerModule(...) on a mapper that was already in use. Jackson 3 removed them all: you configure a builder, call build(), and the result never changes. If you need a variation, rebuild() hands you a new builder pre-loaded with the old settings.
Jackson 2: configure the same object, any time new ObjectMapper()mutable first writeValue…Article serialiser is built and cached mapper.setSerialization…compiles, but had no effect here Jackson 3: configure a builder, then the mapper is final JsonMapper.builder()all settings go here .build()immutable mapper mapper.rebuild()…build()a NEW mapper; the old one is untouched Jackson 3 removes the question “was it configured before or after first use?” by removing the setters. Numbers: Jackson 2 ObjectMapper has 47 such methods, Jackson 3 has none (P02 output below).
The top row is the Jackson 2 hazard, the bottom row the Jackson 3 answer. The red box is not hypothetical: P02ImmutableMapper.java runs it. A Jackson 2 mapper writes an Article once, then gets told to skip nulls:
com.fasterxml.jackson.databind.ObjectMapper m2 = new com.fasterxml.jackson.databind.ObjectMapper();
System.out.println("== Jackson 2: reconfigure after first use ==");
System.out.println("before : " + m2.writeValueAsString(withNull));
m2.setSerializationInclusion(JsonInclude.Include.NON_NULL);
System.out.println("after setSerializationInclusion(NON_NULL) : " + m2.writeValueAsString(withNull));
com.fasterxml.jackson.databind.ObjectMapper fresh2 = new com.fasterxml.jackson.databind.ObjectMapper();
fresh2.setSerializationInclusion(JsonInclude.Include.NON_NULL);
System.out.println("fresh mapper, same setting          : " + fresh2.writeValueAsString(withNull));
Source: P02ImmutableMapper.java (excerpt)
== Jackson 2: reconfigure after first use ==
before : {"articleId":1,"title":"Jackson Deep Dive","tags":["java"],"subtitle":null}
after setSerializationInclusion(NON_NULL) : {"articleId":1,"title":"Jackson Deep Dive","tags":["java"],"subtitle":null}
fresh mapper, same setting          : {"articleId":1,"title":"Jackson Deep Dive","tags":["java"]}
Captured in output/P02ImmutableMapper.txt (excerpt)
The setting was accepted and then ignored: after setSerializationInclusion(NON_NULL) the output still contains "subtitle":null, while a fresh mapper given the same setting skips it. I observed this on 2.23.0; I did not trace the cause through the Jackson source, but it is consistent with the mapper having already built and cached the serialiser for Article on first use. Jackson 3 removes the whole class of problem. The same program on Jackson 3:
tools.jackson.databind.json.JsonMapper nonNull = m3.rebuild()
        .changeDefaultPropertyInclusion(i -> i.withValueInclusion(JsonInclude.Include.NON_NULL))
        .build();
System.out.println("rebuilt NON_NULL  : " + nonNull.writeValueAsString(withNull));
System.out.println("original again    : " + m3.writeValueAsString(withNull));
System.out.println("same instance?    : " + (m3 == nonNull));
Source: P02ImmutableMapper.java (excerpt)
== Jackson 3: rebuild() derives a new mapper ==
original          : {"articleId":1,"subtitle":null,"tags":["java"],"title":"Jackson Deep Dive"}
rebuilt NON_NULL  : {"articleId":1,"tags":["java"],"title":"Jackson Deep Dive"}
original again    : {"articleId":1,"subtitle":null,"tags":["java"],"title":"Jackson Deep Dive"}
same instance?    : false
Captured in output/P02ImmutableMapper.txt (excerpt)
The original keeps its behaviour, rebuild() produces a different object, and nothing can change under a thread that is using the first one. The count at the top of the output file is the blunt version of the same fact: the Jackson 2 ObjectMapper has 47 distinct mutator-style method names, the Jackson 3 one has none (the single match, registeredModules, is a getter).
Going deeper: the builder, rebuild() and modules

Everything you used to do after construction is now a builder call: enable(...)/disable(...) for features, addModule(...) for modules, addMixIn(...) for mix-ins, changeDefaultPropertyInclusion(...) for null handling. Because the finished mapper is thread-safe and unchangeable, sharing one across the application is now a guarantee rather than a convention. The official migration guide states that ObjectMapper and JsonFactory are fully immutable in 3.x.

The settings that matter, and the defaults that changed

Most projects need the same handful of settings: tolerate unknown fields, skip nulls, choose a naming style, optionally pretty-print. Before the recipe, it is worth knowing that Jackson 3 changed several defaults, because an upgrade changes behaviour even if you do not touch a line. P04ConfigRecipes.java reads each default straight from the feature enums of both versions, so nothing here is typed by hand:
== default value of a few features (enabledByDefault) ==
feature                                              Jackson2 Jackson3
DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES    true     false   
SerializationFeature.FAIL_ON_EMPTY_BEANS             true     false   
SerializationFeature.INDENT_OUTPUT                   false    false   
WRITE_DATES_AS_TIMESTAMPS (J2: SerializationFeature, J3: DateTimeFeature) true     false   
DeserializationFeature.FAIL_ON_TRAILING_TOKENS       false    true    
MapperFeature.SORT_PROPERTIES_ALPHABETICALLY         false    true    
Captured in output/P04ConfigRecipes.txt (excerpt)
Five of the six rows flipped. The two with the biggest practical effect:
  • Unknown fields no longer fail. A JSON document with an extra field used to throw UnrecognizedPropertyException; on Jackson 3 it is silently ignored. That is friendlier for evolving APIs and worse for catching typos, because a misspelt field now disappears without an error.
  • Properties are sorted alphabetically. This is the reordering you saw in the first round trip.
The behaviour behind the first row, and the escape hatch the library provides, from the same program:
Jackson 2 default : UnrecognizedPropertyException
Jackson 3 default : accepted unknown field, title=T
Jackson 3 strict  : UnrecognizedPropertyException
builderWithJackson2Defaults : UnrecognizedPropertyException (Jackson 2 behaviour back)
Captured in output/P04ConfigRecipes.txt (excerpt)
JsonMapper.builderWithJackson2Defaults() exists (confirmed with javap) and brings the Jackson 2 behaviour back — in the output above, strict unknown-property handling returns. It is useful during a migration; for new code, choose the settings you want explicitly. The property order comparison from the same file:
order J2 default            : {"articleId":1,"title":"T","tags":["a"],"subtitle":"S"}
order J3 default            : {"articleId":1,"subtitle":"S","tags":["a"],"title":"T"}
order J3 sorting disabled   : {"articleId":1,"title":"T","tags":["a"],"subtitle":"S"}
order J3 Jackson2Defaults   : {"articleId":1,"title":"T","tags":["a"],"subtitle":"S"}
Captured in output/P04ConfigRecipes.txt (excerpt)
Now the recipe itself, one shared mapper with the settings most applications want:
JsonMapper mapper = JsonMapper.builder()
        .enable(SerializationFeature.INDENT_OUTPUT)                       // pretty output
        .propertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE)      // articleId -> article_id
        .changeDefaultPropertyInclusion(
                i -> i.withValueInclusion(JsonInclude.Include.NON_NULL))  // skip nulls
        .build();
Source: P04ConfigRecipes.java (excerpt)
{
  "article_id" : 1,
  "tags" : [ "java", "json" ],
  "title" : "Jackson Deep Dive"
}
round trip articleId = 1
Captured in output/P04ConfigRecipes.txt (excerpt)
Note what is not there: no registerModule, no date flag, no setSerializationInclusion. The null-skipping line is the Jackson 3 spelling: changeDefaultPropertyInclusion(...) replaces setSerializationInclusion(...), and the builder has no method called serializationInclusion (a name that looks right and is not).
Going deeper: other features worth knowing

FAIL_ON_EMPTY_BEANS also flipped to off, so a class with no properties now serialises as {} instead of throwing. FAIL_ON_TRAILING_TOKENS flipped to on: {"a":1} garbage now fails instead of being accepted. WRITE_DATES_AS_TIMESTAMPS moved from SerializationFeature to DateTimeFeature and is off by default (next section). Property naming strategies live in tools.jackson.databind.PropertyNamingStrategies.

Dates: the module you no longer need

Dates are where most people first meet a Jackson 2 error message. A plain Jackson 2 mapper refuses java.time types; adding the JavaTimeModule fixes the error but writes dates as number arrays unless you also disable a flag. Jackson 3 has the support built in, with the sensible output by default. P05JavaTime.java:
com.fasterxml.jackson.databind.ObjectMapper module2 = new com.fasterxml.jackson.databind.ObjectMapper()
        .registerModule(new JavaTimeModule());
System.out.println("Jackson 2 + JavaTimeModule             : " + module2.writeValueAsString(payload));

com.fasterxml.jackson.databind.ObjectMapper fixed2 = new com.fasterxml.jackson.databind.ObjectMapper()
        .registerModule(new JavaTimeModule())
        .disable(com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
System.out.println("Jackson 2 + module + disable(TIMESTAMPS): " + fixed2.writeValueAsString(payload));

// Jackson 3: no module, no flag.
JsonMapper m3 = JsonMapper.builder().build();
System.out.println("Jackson 3, plain JsonMapper            : " + m3.writeValueAsString(payload));
Source: P05JavaTime.java (excerpt)
Jackson 2, no module : InvalidDefinitionException
  Java 8 date/time type `java.time.LocalDate` not supported by default: add Module "com.fasterxml.jackson.datatype:jackson-datatype-jsr310" to enable handling (or disable `MapperFeature.REQUIRE_HANDLERS_FOR_JAVA8_TIMES`) (through reference chain: java.util.LinkedHashMap["published"])
Jackson 2 + JavaTimeModule             : {"published":[2026,11,17],"at":1794876420.000000000}
Jackson 2 + module + disable(TIMESTAMPS): {"published":"2026-11-17","at":"2026-11-17T00:47:00Z"}
Jackson 3, plain JsonMapper            : {"published":"2026-11-17","at":"2026-11-17T00:47:00Z"}
Jackson 3 read LocalDate               : 2026-11-17
class NOT on classpath     : tools.jackson.datatype.jsr310.JavaTimeModule
class present on classpath : com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
Captured in output/P05JavaTime.txt (excerpt)
Read top to bottom: Jackson 2 with no module fails with InvalidDefinitionException; with the module it writes [2026,11,17] and an epoch-seconds number; with the module and the flag disabled it writes ISO-8601 strings; Jackson 3 writes the ISO strings with no module and no flag. The last two lines confirm there is no tools.jackson.datatype.jsr310.JavaTimeModule class at all — a Jackson 2 habit that now fails to compile (transcript further down).
Going deeper: the date features

All date behaviour is controlled by tools.jackson.databind.cfg.DateTimeFeature in Jackson 3, which holds 16 constants (checked with javap), including WRITE_DATES_AS_TIMESTAMPS, WRITE_DURATIONS_AS_TIMESTAMPS, ADJUST_DATES_TO_CONTEXT_TIME_ZONE and WRITE_DATES_WITH_ZONE_ID. Per-field formats still use the shared @JsonFormat annotation.

When parsing fails: checked versus unchecked exceptions

Every read can fail: the JSON is malformed, a number arrives where text was expected. In Jackson 2 those failures are checked exceptions (they extend IOException), so every call needs a try/catch or a throws. In Jackson 3 they extend RuntimeException, which changes how you can write code. Same bad input, both mappers, from P06Exceptions.java:
try {
    m2.readValue(malformed, Article.class);
} catch (com.fasterxml.jackson.core.JsonProcessingException e) {     // checked: the compiler forces this catch
    System.out.println("J2 " + e.getClass().getName());
    System.out.println("   " + e.getOriginalMessage());
    System.out.println("   at line " + e.getLocation().getLineNr() + ", column " + e.getLocation().getColumnNr());
}
try {
    m3.readValue(malformed, Article.class);                         // no throws clause needed on main()
} catch (JacksonException e) {
    System.out.println("J3 " + e.getClass().getName());
    System.out.println("   " + e.getOriginalMessage());
    System.out.println("   at line " + e.getLocation().getLineNr() + ", column " + e.getLocation().getColumnNr());
}
Source: P06Exceptions.java (excerpt)
== class hierarchy ==
J2 JsonProcessingException extends com.fasterxml.jackson.core.JacksonException -> extends java.io.IOException
J3 JacksonException extends java.lang.RuntimeException

== malformed JSON ==
J2 com.fasterxml.jackson.core.JsonParseException
   Unexpected character ('}' (code 125)): expected a valid value (JSON String, Number, Array, Object or token 'null', 'true' or 'false')
   at line 1, column 27
J3 tools.jackson.core.exc.StreamReadException
   Unexpected character ('}' (code 125)): expected a valid value (JSON String, Number, Array, Object or token 'null', 'true' or 'false')
   at line 1, column 27

== wrong value type ==
J2 InvalidFormatException
J3 InvalidFormatException (path: [articleId])
Captured in output/P06Exceptions.txt (excerpt)
The message text and the line and column are identical; the difference is the type. Jackson 3 reports a tools.jackson.core.exc.StreamReadException where Jackson 2 reports a JsonParseException. The practical win is at the end of the program:
java.util.List<Article> parsed = java.util.stream.Stream.of(
                "{\"articleId\":1,\"title\":\"a\"}", "{\"articleId\":2,\"title\":\"b\"}")
        .map(s -> m3.readValue(s, Article.class))                  // does not compile on Jackson 2
        .toList();
Source: P06Exceptions.java (excerpt)
stream + lambda parsed 2 articles with no try/catch
Captured in output/P06Exceptions.txt (excerpt)
Do not carry the old catch over. A Jackson 2 habit is catch (IOException e) around a mapper call. On Jackson 3 the compiler rejects it: exception IOException is never thrown in body of corresponding try statement (from the compiler transcript). Catch JacksonException where you want to handle bad input, and let it propagate everywhere else.
Going deeper: reading the error location and path

getLocation() gives the line and column, and for data-binding errors getPath() lists the property chain; the wrong-type case in the output printed [articleId] as the failing path. That path is what makes an error useful to the caller of your API.

One mapper for the whole application

Here is the rule from the first diagram, with evidence. First, is a single mapper safe to share between threads? P07SharedMapperThreads.java runs 8 threads, each doing 20,000 read-then-write round trips on one JsonMapper, and checks every result:
AtomicInteger wrong = new AtomicInteger();
runThreads(() -> {
    for (int i = 0; i < PER_THREAD; i++) {
        Article a = shared.readValue(json, Article.class);
        if (!"Jackson Deep Dive".equals(a.getTitle()) || !shared.writeValueAsString(a).equals(json)) {
            wrong.incrementAndGet();
        }
    }
});
Source: P07SharedMapperThreads.java (excerpt)
8 threads x 20000 round trips on ONE JsonMapper, wrong results: 0
Captured in output/P07SharedMapperThreads.txt (excerpt)
Zero wrong results across 160,000 round trips. Second, what does it cost to build a mapper for each call instead? The same file times 2,000 reads each way, three rounds so the JIT compiler settles:
round 1: shared 3 ms, new mapper per call 878 ms  (2000 reads each)
round 2: shared 1 ms, new mapper per call 323 ms  (2000 reads each)
round 3: shared 1 ms, new mapper per call 217 ms  (2000 reads each)
Captured in output/P07SharedMapperThreads.txt (excerpt)
2,000 reads of the same small JSON (round 3, indicative) one shared mapper 1 ms new mapper per call 217 ms The shared bar is drawn at a minimum visible width. The point is the order of magnitude, not the exact figure: building the mapper repeats work that a long-lived mapper does once.
The diagram uses the third round. Building a mapper per call was two orders of magnitude or more slower in this run (217 ms against 1 ms, and the shared figure is at the clock’s millisecond resolution). Treat the figures as indicative — they move between runs on a small sandbox, and the rerun I did while preparing this article produced different millisecond values with the same shape — but the order of magnitude is the point: a new mapper repeats work (discovering properties, building serialisers) that a long-lived mapper does once and caches.
The rule, in one line. Build one JsonMapper in a configuration class or a static holder, share it, and derive variants with rebuild() if you truly need them. In a Spring application the framework already builds the shared mapper for you; inject it rather than creating another.
Going deeper: ObjectReader and ObjectWriter

For hot paths, mapper.readerFor(Article.class) and mapper.writerFor(...) return reusable, thread-safe, single-type objects that skip some lookup work. They are also how you apply a setting to one call without touching the shared mapper, for example writerWithDefaultPrettyPrinter() as used earlier.

What breaks when you move from Jackson 2 to Jackson 3

Collecting the traps from the sections above, plus the ones the compiler catches for you. Each row is a Jackson 2 habit; the last column is a real compiler message from the repository’s src/broken files (kept outside the Maven build and compiled on purpose by broken.sh).
Jackson 2 habitOn Jackson 3Compiler says
mapper.setSerializationInclusion(...), configure, enablebuilder only; use changeDefaultPropertyInclusion / enable on the buildercannot find symbol
readValue(new URL(...), T.class)open the stream yourselfno suitable method found for readValue(URL,Class<Object>)
catch (IOException e) around the mappercatch JacksonExceptionexception IOException is never thrown
registerModule(new JavaTimeModule())delete it; built inpackage tools.jackson.datatype.jsr310 does not exist
SerializationFeature.WRITE_DATES_AS_TIMESTAMPSDateTimeFeature.WRITE_DATES_AS_TIMESTAMPScannot find symbol: variable WRITE_DATES_AS_TIMESTAMPS
The full transcript, verbatim from Broken-compile-errors.txt (first two files shown):
=== Broken1MutateAfterBuild.java ===
Broken1MutateAfterBuild.java:9: error: cannot find symbol
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
              ^
Broken1MutateAfterBuild.java:10: error: cannot find symbol
        mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
              ^
Broken1MutateAfterBuild.java:11: error: cannot find symbol
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
              ^
3 errors

=== Broken2ReadValueUrl.java ===
Broken2ReadValueUrl.java:7: error: no suitable method found for readValue(URL,Class<Object>)
        Object o = mapper.readValue(new java.net.URL("https://example.com/a.json"), Object.class);
                         ^
1 error
Captured in output/Broken-compile-errors.txt (excerpt)
The compile errors are the easy part: they stop the build. The dangerous changes are the default changes from earlier (alphabetical order, unknown fields ignored, trailing tokens rejected), which compile fine and change behaviour. Run your JSON contract tests after the upgrade, not just the compiler.
Going deeper: the full migration checklist

This article covers the mapper itself. Renamed types (JsonSerializer to ValueSerializer, SerializerProvider to SerializationContext), the new package for the streaming layer, and module changes are in the migration guide and its companion repository.

Should you move to Jackson 3?

An honest answer. Not necessarily today. Jackson 2.23.0 was uploaded to Maven Central the same day as Jackson 3.3.0, so Jackson 2 is clearly still being released and nothing here is an emergency. Choose Jackson 3 for new code and for frameworks that already use it (Spring Boot 4 does). Move an existing Jackson 2 application when you have contract tests for your JSON, because the changes that bite are the silent default changes, not the compile errors. And if you only use ObjectMapper through a framework, the framework’s own upgrade is the decision, not yours.

AI prompts for Jackson ObjectMapper

Three prompts for generating mapper code for your own classes with an AI assistant. Always compile and run the result; the verified examples above are what to compare it against.
Generate POJO round-trip code

I have this POJO class: [paste your class here]. I am using Jackson 3.3.0. Generate five working examples using JsonMapper.builder().build(): serialise an instance to a String, serialise to a File, serialise to an OutputStream, deserialise from a String, and deserialise from an InputStream. For any LocalDate or Optional fields, confirm no extra modules are needed. Include a sample JSON output comment after each serialise call.

What it does: produces five copy-paste-ready snippets covering the common I/O variants for your exact class, with sample JSON output as comments so you can verify the mapping without running the code first.

When to use it: when adding a new DTO to a Jackson 3 project, or when onboarding teammates who need concrete examples rather than documentation links.

Configure a REST client mapper

I am writing a typed REST client in Java using Jackson 3.3.0 that calls a third-party API. Configure a JsonMapper using the builder pattern with these requirements: unknown fields must not throw an exception, dates must serialise as ISO-8601 strings not epoch milliseconds, null fields must be excluded from outbound request bodies, and single-quoted JSON must be accepted if the target API is lenient. Add a one-line comment on every builder call explaining the exact runtime effect of that setting.

What it does: generates a fully commented JsonMapper.builder() block for REST client usage, each setting explained in plain English. Remember from the defaults table above that on Jackson 3 the first two requirements are already the defaults, so a good answer should say so rather than add redundant lines.

When to use it: when writing a client against an external API that may evolve its schema and where you want clean, minimal outbound payloads.

Deserialise generic collections

Using Jackson 3.3.0, show me how to deserialise these four JSON structures into typed Java collections: a JSON array into List<OrderDto>, a JSON object into Map<String, OrderDto>, a paginated wrapper like {"content":[...],"totalElements":100} into a generic Page<OrderDto> class, and an array of unknown objects into List<Map<String, Object>>. Explain why TypeReference is required for each case and what goes wrong if you pass List.class directly.

What it does: provides four complete examples with working TypeReference patterns and explains why List.class produces an untyped list of LinkedHashMap (shown in the output earlier).

When to use it: when consuming paginated REST APIs or batch endpoints whose root element is a collection or generic wrapper, or when readValue(json, List.class) compiles but throws ClassCastException later.

Conclusion

ObjectMapper is the foundation of JSON handling in Java, and the rules are short: create one mapper, configure it once through the builder, share it across threads, pass a TypeReference for generic types, and check the changed defaults when you move to Jackson 3. Everything above was executed on Jackson 2.23.0 and 3.3.0, and every output line can be regenerated with one script. The next articles in this series build on this foundation:

Further reading

No Comments yet!

This site uses Akismet to reduce spam. Learn how your comment data is processed.