Skip to content
javahacks.dev
Micronaut

Micronaut Serialization Instead of Jackson Setup Guide

Switch a Micronaut 4 application from Jackson databind to Micronaut Serialization: dependencies, the Serdeable annotation, differences, GraalVM and limits.

6 min read
Summarize in AI
Flat illustration of startup time of a JVM compared with a native image, with the Spring, Quarkus, OpenJDK and Kubernetes logos.

Jackson databind discovers the properties of a class by reflection at run time. That works well on a standard JVM and gets awkward on a GraalVM native image, where every reflectively used class has to be declared in advance. Micronaut Serialization takes the same approach Micronaut takes to dependency injection: do the discovery while the code compiles, and generate plain classes for the result. This post covers Micronaut 4, from the dependency changes to the behaviour differences you have to check.

Dependencies

XML
<dependency>
  <groupId>io.micronaut.serde</groupId>
  <artifactId>micronaut-serde-jackson</artifactId>
  <scope>compile</scope>
</dependency>

<!-- in the compiler plugin's annotationProcessorPaths -->
<path>
  <groupId>io.micronaut.serde</groupId>
  <artifactId>micronaut-serde-processor</artifactId>
</path>

The processor reads annotated types during compilation and writes a serializer and deserializer class for each. The micronaut-serde-jackson module keeps the Jackson core streaming parser for JSON syntax, but not databind, so there is no reflection-based mapping layer. A project created by Micronaut Launch with the serialization feature has both lines already, as in the Micronaut tutorial. Remove micronaut-jackson-databind when you switch, or the two compete for the HTTP layer.

Mark the types

java
@Serdeable
public record OrderView(long id, String customer, @JsonProperty("total_cents") long totalCents) { }
java
@Controller("/orders")
class OrderController {

    @Get("/{id}")
    OrderView get(long id) {
        return new OrderView(id, "ada", 2500);
    }
}

@Serdeable is the instruction to generate code for the type. Return a class without it from a controller and the request fails with an error that no serializer exists for that type. This is the most common first failure after the switch, and it is a feature: under Jackson, forgetting nothing at all would work until the native image broke. To restrict generation to one direction, use @Serdeable.Serializable for output only or @Serdeable.Deserializable for input only. Records are supported, as are classes with a constructor or a builder.

For a class you cannot annotate, such as a DTO from a client library, import it:

java
@SerdeImport(ThirdPartyDto.class)
class SerdeConfig { }

What carries over

The common Jackson annotations are understood: @JsonProperty, @JsonIgnore, @JsonInclude, @JsonCreator, @JsonAlias, @JsonFormat, and @JsonTypeInfo with @JsonSubTypes for the straightforward polymorphic cases. Dates and times, enums, optionals, collections and maps work, and the JSON produced for an ordinary object matches what Jackson would write. Existing DTOs therefore often need only the extra annotation.

What changes

Jackson habitIn Micronaut Serialization
Inject com.fasterxml.jackson.databind.ObjectMapperInject io.micronaut.serde.ObjectMapper
Serialize any class without preparationThe class needs @Serdeable or @SerdeImport
Register Jackson modules for exotic typesWrite a Serializer<T> and Deserializer<T> as beans
Mixins and @JsonAnyGetter tricksLimited or unsupported; check each
Behaviour set with ObjectMapper.configure(...)Configuration properties under micronaut.serde

The row that costs the most time is the first. Code written as mapper.readValue(json, Foo.class) against Jackson's type will not compile once the dependency is gone, and the replacement type has a similar but not identical API. Search for com.fasterxml.jackson.databind before you start, and count the hits. Fifty hits in tests and utilities is an afternoon. Hundreds spread over custom modules is a project. Compare with the failure modes catalogued for Jackson in unrecognized fields, since the same payload problems appear with a different message.

Why bother

On a native image the benefit is large. There is no reflection configuration to write and maintain for your DTOs, binaries are smaller and startup is faster, which follows the compile-time philosophy in compile-time DI and the native image build. On a plain JVM the gain is smaller: slightly quicker startup and lower memory. The Micronaut project reports throughput in the same range as Jackson databind, and that is a claim to test against your own payload sizes before you rely on it.

A migration order that keeps the build green

Start by adding the serde dependency and the processor while Jackson databind stays in place, then switch the default serializer for the HTTP layer in one change. Run the test suite, and read the failures in groups: a missing @Serdeable is a one line fix, a changed ObjectMapper type is a mechanical edit, and a failing custom module is the real work. Fix the first two kinds across the codebase before touching the third. If your tests compare JSON strings, expect a few differences in property order or in how nulls are written, and decide whether the test or the output is right. Client-side code is the next place to look. A declarative @Client interface that returns a DTO needs that DTO annotated too, because the response is deserialized by the same machinery. Finally, build the native image early and run it once, even if you deploy to a JVM today, because it is the only way to find a type that the processor did not see.

Third-party DTOs deserve a deliberate decision. @SerdeImport on a configuration class works for a handful of classes. For a large generated client with hundreds of model classes, import them in bulk by package, or keep a thin mapping layer in your own code so the library types never reach the controller signature.

Writing a serializer by hand

Some types have no sensible default form, such as a value object that should appear as a bare string. Micronaut Serialization expresses that as a pair of beans, and the compiler checks the types:

java
@Singleton
class SkuSerializer implements Serializer<Sku> {
    @Override
    public void serialize(Encoder encoder, EncoderContext context,
                          Argument<? extends Sku> type, Sku value) throws IOException {
        encoder.encodeString(value.code());
    }
}

@Singleton
class SkuDeserializer implements Deserializer<Sku> {
    @Override
    public Sku deserialize(Decoder decoder, DecoderContext context,
                           Argument<? super Sku> type) throws IOException {
        return new Sku(decoder.decodeString());
    }
}

Both are ordinary beans, so a missing annotation processor or a disabled bean produces the errors described in Micronaut no bean of type. Note the contrast with Jackson, where the same job needs a module registration; here the container finds them by type.

Checking the result

After the switch, write one test per DTO family that serializes an object and compares the JSON to a literal string, and one that reads the literal back. Under the Micronaut test framework, inject the serde ObjectMapper and call writeValueAsString and readValue. These tests are cheap, and they pin the wire format, which is the contract your clients depend on. A rename of a field during the migration shows up here and not in a customer's integration.

Going back, or doing both

If you need a Jackson databind feature that has no equivalent, depend on micronaut-jackson-databind instead and remove the serde modules. During a migration both can be on the classpath, with one selected as the default for the HTTP layer, so you can move controllers over a few at a time instead of all at once.

Where staying on Jackson makes sense

A service that never builds a native image and relies on Jackson modules for unusual types has little to gain and some work to lose. The same goes for a team whose DTO layer uses mixins heavily. For the wider picture, see Micronaut Data and REST. The primary sources are the Micronaut Serialization guide and the Micronaut documentation.

Also inSpring MVC
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.