JSON and Jackson

Every getter is a property, unknown and missing fields, java.time without its module, and the id JavaScript rounded to a different record.

11 min read🧰 Exceptions, I/O and Reflection

Almost every Java service turns objects into JSON and back, many thousands of times a second, and almost nobody writes that code. Jackson does it. Spring calls it on every request body and every response, and it is so reliable that people forget it is making decisions — about which fields exist, what a missing value means, and how a number is written.

This lesson is about those decisions, because each one has a default, and several of the defaults are how data leaks or quietly changes.

All the output below is from Jackson 2.18.2 on a JVM, with a plain new ObjectMapper() unless it says otherwise.

What Jackson looks at

Jackson does not read your fields directly. By default it builds a property for every public getter, and for every public field:

User.javajava
public static class User {
    private long id;
    private String email;
    private String passwordHash;
    public User() {}
    public User(long id, String email, String passwordHash) { /* assigns all three */ }
    public long getId() { return id; }
    public String getEmail() { return email; }
    public String getPasswordHash() { return passwordHash; }
}
plaintext
{"id":9007199254740993,"email":"ana@example.com","passwordHash":"$2a$10$abc"}

The password hash is in the response. Nobody decided to publish it. Somebody added a getter because some other code needed it, and a getter is a decision about your JSON whether you meant it to be or not.

There are two fixes, and the second is the one that lasts:

SafeUser.javajava
public static class SafeUser {
    // ...the same fields and constructor
    public long getId() { return id; }
    public String getEmail() { return email; }
    @JsonIgnore public String getPasswordHash() { return passwordHash; }
}
plaintext
{"id":42,"email":"ana@example.com"}

@JsonIgnore works, and it is a blocklist: the next sensitive field someone adds is published until somebody remembers the annotation. The durable fix is not to serialize the entity at all. Map it to a response class that contains only what the API promises — the REST course's lesson on DTOs makes that case in full. Then a new field on the entity changes nothing on the wire until someone adds it to the DTO on purpose.

Unknown fields: strict or lenient

A client sends a field your class does not have:

plaintext
{"sku":"A1","quantity":2,"coupon":"FREE"}

A plain ObjectMapper refuses it:

plaintext
UnrecognizedPropertyException: Unrecognized field "coupon" (class JsonDemo$Order), not marked as ignorable (2 known properties: "quantity", "sku"])

Turn that off with FAIL_ON_UNKNOWN_PROPERTIES = false and the same input reads as sku=A1 quantity=2, with the coupon silently dropped.

Spring Boot's auto-configured mapper turns it off for you. That is the right default for most APIs — it lets a client send a newer version of a request to an older server, and lets you add fields to responses without breaking old clients — and it has a cost worth knowing: a client that misspells a field name (quantitiy) gets no error. The value is simply ignored, and the request succeeds with the default.

Missing fields are not errors

Which leads to the more dangerous case:

plaintext
input:  {"sku":"A1"}
result: quantity=0

No exception. A missing int becomes 0, a missing boolean becomes false, a missing object becomes null. Jackson cannot distinguish "the client sent zero" from "the client sent nothing", and for an order quantity those mean very different things.

Immutable classes need to tell Jackson how

A class with only a constructor and final fields:

java
public static class Immutable {
    private final String name;
    public Immutable(String name) { this.name = name; }
    public String getName() { return name; }
}
plaintext
MismatchedInputException: Cannot construct instance of `JsonDemo$Immutable` (although at least one Creator exists): cannot deserialize from Object value (no delegate- or property-based Creator)

Jackson's default is: call the no-argument constructor, then set properties. With no such constructor, it needs to be told which constructor parameter is which JSON property — @JsonCreator with @JsonProperty("name") on the parameter, or compiling with -parameters and registering the parameter-names module, which Spring Boot does. Java records are handled directly by Jackson 2.12 and later.

Dates, and the module you did not add

plaintext
InvalidDefinitionException: Java 8 date/time type `java.time.Instant` not supported by default: add Module "com.fasterxml.jackson.datatype:jackson-datatype-jsr310" to enable handling

A plain ObjectMapper cannot write an Instant. The error is admirably clear, and it is the reason for the most common Jackson bug report: code that works inside Spring, where the module is registered for you, fails in a unit test or a batch job that creates its own new ObjectMapper().

With the module, decide the format deliberately. Write instants as ISO-8601 strings in UTC ("2026-09-13T10:00:00Z"): readable, sortable as text, and unambiguous. Numeric timestamps save a few bytes and invite the milliseconds-or-seconds argument with every client.

Numbers that change on the way through

Two runs, two surprises. First, money:

plaintext
{"asDouble":0.30000000000000004,"asDecimal":0.3}

0.1 + 0.2 as a double is not 0.3, and Jackson writes exactly what the double holds. Keep money in BigDecimal, or in integer minor units (paise, cents) as a long.

Second, and far less known — the User above had the id 9007199254740993. Jackson wrote it correctly. Here is what a JavaScript client does with that response:

plaintext
> JSON.parse('{"id":9007199254740993,"email":"ana@example.com"}').id
9007199254740992

The id changed by one. JSON numbers have no size limit, but JavaScript reads every number as a 64-bit double, which represents integers exactly only up to 2^53 − 1 (9,007,199,254,740,991). A Java long goes far beyond that. Snowflake-style ids and database sequences past that range are silently rounded in every browser, and the client then asks for, updates or deletes a different record.

One ObjectMapper, shared

An ObjectMapper is expensive to create and cheap to use: it caches what it learns about each class. It is thread-safe once configured, so an application should create one and share it — which is what injecting Spring's does.

Serializing the same small object 20,000 times, twice:

plaintext
round 0: new mapper each call 421 ms, shared mapper 26 ms (20,000 calls)
round 1: new mapper each call 197 ms, shared mapper 5 ms (20,000 calls)

Forty times slower per call on the warm round, and the first round includes JIT warm-up for both. A new ObjectMapper() inside a request handler is a slow leak of CPU that shows up nowhere except in a flame graph. The exact ratio is one machine's; the direction is not.

The one rule that goes with sharing: configure it before you share it. Changing a shared mapper's settings while other threads are using it is not supported, and copy() exists for the case where one caller needs different settings.

Why not Java serialization

Java has its own built-in object serialization (Serializable, ObjectInputStream). It is not an alternative to JSON for anything that crosses a trust boundary. Deserializing a stream can instantiate arbitrary classes on the classpath and run code in them, and it has been the root of remote code execution vulnerabilities in widely used libraries. JSON mapped onto classes you chose is a much smaller attack surface.

Jackson has its own version of that trap: polymorphic typing from input, where the JSON names the class to instantiate. Enabling it globally (the old enableDefaultTyping) produced a long series of CVEs for the same reason. If a type hierarchy must be deserialized, use @JsonTypeInfo with an explicit, closed list of subtypes.

Under the hood: how Jackson decides which constructor to call, and why an open type hierarchy is dangerous

The "immutable classes need to tell Jackson how" section above shows the error Jackson gives when a class has no default constructor. What actually happens when you fix it with @JsonCreator is worth going into, because it is a different code path from everything else in this lesson — everything above is about serialisation, reading properties off an object that already exists. Constructor binding is about deserialisation, building the object in the first place, and Jackson does not do it the way you'd guess.

CreateOrder.javajava
public record CreateOrder(
    @JsonProperty("sku") String sku,
    @JsonProperty("quantity") int quantity) {
 
    @JsonCreator
    public CreateOrder { /* compact constructor: validate here */
        if (quantity <= 0) throw new IllegalArgumentException("quantity must be positive");
    }
}

With a no-arg-constructor-then-setters class, Jackson assigns properties one at a time as it encounters them in the JSON token stream — the object exists, half-built, between each setter call. A constructor has no such thing as "half called". So when Jackson sees @JsonCreator with @JsonProperty-annotated parameters (or parameter names read via -parameters and the parameter-names module, mentioned above), it does not try to call the constructor incrementally. It builds a PropertyValueBuffer, reads every JSON property into that buffer as it arrives — in whatever order the JSON actually has them, which is never guaranteed to match constructor parameter order — and only once every required parameter has a value (or the JSON object ends) does it invoke the constructor exactly once, with the complete argument list. The buffering exists specifically because "JSON key order" and "constructor parameter order" are two independent things Jackson cannot assume line up.

This has a consequence worth naming: a class deserialised through constructor binding gets its invariant checks — a compact constructor's validation, a plain constructor's Objects.requireNonNull — run exactly once, on a fully-formed argument list, for every object Jackson builds. There is no intermediate state a bug could observe, unlike setter-based binding where code running between two setter calls (a poorly timed @PostConstruct, a listener) could see an object with only some of its fields set.

The matching is also by name, not position: @JsonProperty("sku") on the second parameter and @JsonProperty("quantity") on the first would still bind correctly even though the JSON puts sku first, because the buffer resolves each incoming property against the declared name before the single constructor call — reordering a constructor's parameter list to match new API documentation does not silently shuffle which JSON value lands where.

Polymorphic input needs a related but different mechanism: something has to say which subtype a piece of JSON is. @JsonTypeInfo adds a type discriminator — as = As.PROPERTY writes an extra field ("type":"CARD"); EXISTING_PROPERTY reuses a field the class already has; WRAPPER_OBJECT/WRAPPER_ARRAY wrap the payload instead. Paired with @JsonSubTypes, that discriminator value is resolved against an explicit, closed list of allowed classes — Jackson never constructs a class the input alone names, only one from the list you wrote. This is precisely the design constraint the closing paragraph of this lesson gestures at: the historical enableDefaultTyping setting removed that closed list, turning the discriminator into any fully-qualified class name the input supplies, which Jackson then resolves with something equivalent to Class.forName and instantiates — the same "the input names the class to run" shape that makes Java's own object serialization a remote-code-execution surface, reached this time through a JSON string instead of a binary stream.

Try it yourself

Does parameter order matter?

A teammate adds a new field, String promoCode, to both the JSON contract and the middle of CreateOrder's constructor parameter list — between sku and quantity — to match where it appears in the team's API docs. Each parameter still carries its own @JsonProperty. Using the constructor-binding mechanism above: does moving quantity from position 2 to position 3 risk Jackson passing the wrong value into the wrong parameter for existing clients that still send {"sku":"A1","quantity":2}?

No — binding is by declared name, not by position

PropertyValueBuffer resolves each incoming JSON property against the @JsonProperty name declared on each constructor parameter, and only assembles the final argument list — in the constructor's actual parameter order — once every property has a value. Reordering the parameters changes where each name sits in the constructor's argument list, but Jackson rebuilds that argument list from the buffer by name every time, so sku and quantity still land in the right constructor parameters regardless of which position they now occupy or what order the client sent them in. The one thing that would break existing clients is renaming a @JsonProperty value itself — that changes what name Jackson looks for in the incoming JSON, which parameter order never does.

Misconceptions

  • "@JsonCreator binds a constructor the same way setters bind fields — one property at a time as it arrives." No — properties are buffered as they arrive and the constructor is called exactly once, with the complete list, only after every required value is known. There is no partially-constructed object at any point.
  • "A @JsonTypeInfo-annotated class is exactly as risky as enableDefaultTyping." Only when the subtype resolution is open. Paired with @JsonSubTypes (or an equivalent closed TypeIdResolver), the discriminator only ever selects from a fixed list you wrote down and reviewed — the danger is specifically an unbounded type-id resolution, not the presence of a discriminator field.

Sources

  • Jackson-databind project documentation — @JsonCreator, property-based creators and ValueInstantiator.
  • Jackson-annotations project documentation — @JsonTypeInfo and @JsonSubTypes.
  • Jackson-databind project documentation and issue history on polymorphic type handling and enableDefaultTyping.
Progress is saved on this device and to your account when signed in.