Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 119 ยท Data Formats

Advanced Jackson

Master Jackson annotations (@JsonProperty, @JsonIgnore, @JsonInclude, @JsonFormat), the JsonNode tree model, unknown fields, polymorphic types and custom serializers.

In JSON with Jackson your Java classes and the JSON had the same shape: same names, same structure. Real APIs are rarely that polite. A partner sends snake_case keys, a field must never leave the server, dates arrive as "01.03.2025", a response holds a list of different kinds of shapes, and some payloads are so irregular that you only want two values out of them.

This lesson gives you the tools for all of that: annotations that tune how a class maps to JSON, settings for unknown properties, the tree model (JsonNode) for JSON without a fixed shape, polymorphic types with @JsonTypeInfo, and custom serializers for the rare case where none of the above is enough. Everything runs on Jackson 2.22.

Annotations for renaming, hiding and formatting

Jackson's annotations live in com.fasterxml.jackson.annotation. You put them on record components, fields, getters or the class itself. These are the ones you will use most:

Annotation Effect
@JsonProperty("name") Use a different JSON key for this property.
@JsonAlias({"a", "b"}) Also accept these keys when reading (writing still uses the main name).
@JsonIgnore Leave this property out in both directions.
@JsonInclude(Include.NON_NULL) Skip the property when it is null (also NON_EMPTY, NON_DEFAULT).
@JsonFormat(pattern = "...") Format dates, numbers or enums in a specific way.
@JsonPropertyOrder({...}) Fix the order of keys in the output.
@JsonIgnoreProperties(ignoreUnknown = true) Don't fail on keys the class doesn't know.
Java Shaping JSON with annotations

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.

Four things happened in the output: userName became user_name, the password hash never appeared, the null nickname was skipped, and the date used the custom pattern. When reading, @JsonIgnore means the hash stays null even if a client sends one, which is exactly what you want for a field that must only be set on the server.

@JsonIgnore is not a security boundary on its own. It is easy to forget on a new field, and easy to undo with a well-meant refactoring. For API responses, the safer design is a dedicated response record (a DTO) that simply has no password field at all. See Layered Architecture.

Changing every name at once

If a whole API uses snake_case, annotating each property is tedious. Set a naming strategy on the mapper instead:

Java
ObjectMapper mapper = JsonMapper.builder()
    .propertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE)   // userName -> user_name
    .build();

Other built-in strategies include KEBAB_CASE, LOWER_CAMEL_CASE (the default), UPPER_CAMEL_CASE and LOWER_DOT_CASE. An explicit @JsonProperty still wins over the strategy.

Unknown properties

By default, a key your class doesn't know causes an UnrecognizedPropertyException. That strictness is useful inside one team, but harmful between systems: when a server adds a field, every strict client breaks. The guideline many teams follow is be strict in what you send, tolerant in what you accept. You have three options:

  • Per class: @JsonIgnoreProperties(ignoreUnknown = true) on the record or class.
  • Per mapper: .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) on the builder. Spring Boot's auto-configured mapper already does this.
  • Keep them: @JsonAnySetter on a method or map field collects unknown keys, and @JsonAnyGetter writes them back out. Useful for proxies that must pass data through unchanged.
Java Strict, tolerant and collecting

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 flexible version kept z and label and wrote them back out next to x and y, so nothing was lost on the way through.

The tree model: JsonNode

Sometimes you don't want a class at all: you need three values from a large, deeply nested response, or the structure varies, or you are writing a tool that inspects arbitrary JSON. mapper.readTree(json) parses the document into a tree of JsonNode objects: ObjectNode for objects, ArrayNode for arrays, and value nodes for the rest.

Navigation methods to know:

Method Behavior
node.get("key") / get(index) The child, or null if missing.
node.path("key") / path(index) The child, or a MissingNode if missing, so chains never throw.
node.at("/items/0/price") Follows a JSON Pointer path (RFC 6901).
asText(), asInt(), asDouble(), asBoolean() Converts the value, with a default for missing or mismatched nodes.
isMissingNode(), isNull(), isArray(), isObject() Checks what you have.
for (JsonNode child : node) Iterates array elements (or object values).
properties() The key/value entries of an object.

You can also build trees (mapper.createObjectNode().put(...)), and convert between trees and classes with treeToValue and valueToTree.

Java Reading and building JSON trees

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 get versus path difference matters. order.get("coupon").asText() would throw a NullPointerException; order.path("coupon").asText() returns an empty string. Use path for chains and check isMissingNode() when "absent" and "empty" must be told apart.

The tree model is also the easiest way to patch JSON: read it into a tree, change a few nodes with ObjectNode.put, remove or set, and write it back. Properties you never touched survive unchanged, which a round trip through a record would not guarantee.

Polymorphic types

Suppose an API returns a list of shapes, where each shape can be a circle or a rectangle with different fields. In Java that is a natural fit for a sealed interface with record implementations. But when Jackson reads {"radius": 2} into a Shape, it can't know which class to create. You have to put a type id in the JSON and tell Jackson how to map it:

  • @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type") says: add a property called type holding a logical name.
  • @JsonSubTypes lists the subclasses and their names.
Java A list of different shapes

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 writerFor(new TypeReference<List<Shape>>() {}) when writing the list. Because of type erasure, a plain writeValueAsString(drawing) only sees a List of objects and may not include the type ids. Telling Jackson the declared element type makes the output reliable. Reading back, the pattern-matching switch handles each shape type, and the compiler checks that every permitted subtype is covered.

An unknown type id ("triangle") fails with an InvalidTypeIdException. If you prefer to ignore unknown types, @JsonTypeInfo has a defaultImpl attribute for a fallback class.

Never use type ids that are class names taken from untrusted input (JsonTypeInfo.Id.CLASS, or the old enableDefaultTyping()). An attacker could ask Jackson to create any class on your classpath, and many known remote-code-execution vulnerabilities worked exactly that way. Logical names with an explicit @JsonSubTypes list, as above, are safe.

Custom serializers and deserializers

Annotations cover most needs. For a value type with its own textual form, write a custom serializer. Say your API represents money as one string, "12.50 EUR", but in Java it is a Money record with a BigDecimal and a Currency.

There are two ways:

  1. Simple: @JsonValue on a method tells Jackson to write the object as that method's result, and @JsonCreator on a static factory tells it how to read it back. Good when you own the class.
  2. Full control: extend StdSerializer<T> and StdDeserializer<T>, and register them in a SimpleModule. Works for classes you can't annotate (from a library) and for complex formats.
Java Money as a single string, two ways

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.

12.50 stayed 12.50 because BigDecimal.toPlainString() keeps the scale, and the Fahrenheit reading of 212 became exactly 100 ยฐC. The deserializer reads the value as a tree first, which is the easiest way to write one; for very high-throughput code you would read tokens directly from the JsonParser instead.

Mix-ins: annotations without touching the class

If you can't edit a class but only want to rename or hide a few properties, a full serializer is overkill. A mix-in is an interface or abstract class whose annotations Jackson applies to the target class, as if they were written there:

Java
abstract class LibraryUserMixIn {
    @JsonIgnore abstract String getPasswordHash();
    @JsonProperty("display_name") abstract String getName();
}

ObjectMapper mapper = JsonMapper.builder()
    .addMixIn(LibraryUser.class, LibraryUserMixIn.class)
    .build();

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A component is declared @JsonProperty("zip") @JsonAlias("postcode") String postalCode. Which key appears when the object is written?

    JsonProperty sets the name used for writing and reading. JsonAlias only adds extra names that are accepted when reading.
  2. 2. root is a JsonNode for {"a": {}}. What does root.path("a").path("b").asText() return?

    path() never returns null; for a missing child it returns a MissingNode, whose asText() is an empty string. get("b") would have returned null instead.
  3. 3. With @JsonTypeInfo(use = Id.NAME, property = "type") and subtypes circle and rect, what happens when reading {"type": "hexagon"} as a Shape?

    The type id is not in the JsonSubTypes list, so Jackson can't decide which class to create, unless you configure a defaultImpl fallback.
  4. 4. Why is JsonTypeInfo.Id.CLASS dangerous with input from clients?

    Class-name type ids give the sender control over which classes are created. Logical names with an explicit subtype list are the safe choice.
  5. 5. When should you prefer @JsonValue and @JsonCreator over a custom StdSerializer?

    The annotations are the shortest solution for value types you control. For library classes or complex structures, a serializer registered in a module is the right tool.

Summary

  • Annotations tune the mapping: @JsonProperty renames, @JsonAlias accepts extra names, @JsonIgnore hides, @JsonInclude(NON_NULL) skips nulls, @JsonFormat formats dates and numbers, @JsonPropertyOrder orders keys.
  • A naming strategy such as PropertyNamingStrategies.SNAKE_CASE renames everything at once.
  • Control unknown properties per class (@JsonIgnoreProperties(ignoreUnknown = true)), per mapper (FAIL_ON_UNKNOWN_PROPERTIES), or collect them with @JsonAnySetter/@JsonAnyGetter.
  • The tree model (readTree, JsonNode) handles JSON without a fixed shape. Use path() for safe chains and at("/json/pointer") for deep values.
  • Polymorphic types need a type id: @JsonTypeInfo(use = Id.NAME) plus @JsonSubTypes. Never accept class names from untrusted input.
  • For special formats, use @JsonValue/@JsonCreator on your own types, or StdSerializer/StdDeserializer in a SimpleModule; mix-ins annotate classes you can't edit.

Next: XML Processing covers the other big data format, with DOM, XPath, streaming and the security settings every XML parser needs.