Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 38 ยท HTTP Server and Clients

JSON and Serialization

How Micronaut turns objects into JSON and back: Micronaut Serialization with @Serdeable, records, Jackson annotations, naming, dates, nulls and third-party types.

Almost every Micronaut API sends and receives JSON, so the way objects are converted matters for correctness, speed and native images. Micronaut offers two stacks. Micronaut Serialization (the default in new projects) generates the code for reading and writing your types at compile time, with no reflection. Jackson Databind is the classic reflection-based library, still available through a module when you need its full feature set.

The real framework code below is read-only, since Micronaut is not installed on this site. The runnable programs are Java stand-ins: a record serializer that mirrors what generated code does (including snake-case naming and nested data), and a parser that binds JSON text back to a record with clear error messages.

Marking types as serializable

With Micronaut Serialization, a type must opt in with @Serdeable, so the annotation processor knows to generate code for it:

Java
import io.micronaut.serde.annotation.Serdeable;

@Serdeable
public record Book(long id, String title, List<String> authors, LocalDate published) {}

That is all that is needed for a record or a class with a constructor and getters. Controllers can now return Book and accept @Body Book, and the JSON is produced and read by generated code. If you forget @Serdeable, the application fails at runtime with an error saying that no serializer exists for the type, often the first surprise for newcomers.

Variations:

Annotation Meaning
@Serdeable Serialize and deserialize
@Serdeable.Serializable Output only (responses)
@Serdeable.Deserializable Input only (request bodies)
@SerdeImport(Type.class) Make a third-party class serializable without editing it
@Introspected Alternative opt-in used by Jackson Databind mode and bean introspection

Using @Serdeable.Serializable on response types and @Serdeable.Deserializable on request types means less generated code, which matters for large APIs and for the size of a native image.

Controlling the JSON shape

Micronaut Serialization understands the usual Jackson annotations (add the micronaut-serde-jackson module, which new projects include):

Java
@Serdeable
public record Account(
        long id,
        @JsonProperty("full_name") String fullName,
        @JsonIgnore String passwordHash,
        @JsonInclude(JsonInclude.Include.NON_NULL) String nickname,
        @JsonFormat(pattern = "yyyy-MM-dd") LocalDate joined) {}
  • @JsonProperty renames a field in the JSON.
  • @JsonIgnore hides it. Always hide secrets this way, or use a separate response type.
  • @JsonInclude omits nulls or empty values.
  • @JsonFormat changes date and number formats.

You can set a global naming rule and inclusion policy in application.yml:

YAML
jackson:
  property-naming-strategy: SNAKE_CASE
micronaut:
  serde:
    serialization:
      inclusion: NON_ABSENT

With SNAKE_CASE, a Java property fullName appears as full_name. Java 8 date and time types (LocalDate, Instant, Duration) are supported out of the box and are written as ISO-8601 strings by default.

Two JSON stacks

Micronaut Serde Generated code, no reflection, native friendly.
Jackson Databind Reflection based, huge feature set.

New projects default to Micronaut Serde.

1 / 2

Design tips

  • Use separate request and response types (DTOs). An Account entity should not double as the JSON the world sees; a response record can omit internal fields and a request record can omit generated ids.
  • Prefer records. They are immutable and have exactly the constructor shape the serializer wants.
  • Be careful with polymorphism. Use @JsonTypeInfo and @JsonSubTypes only when needed, and test them, because they interact with native image generation.
  • Do not serialize entities with lazy collections directly. Convert them to DTOs first.
  • Use Optional sparingly in fields. null or an absent property is clearer in JSON than nested Optional types.

Stand-in 1: writing records as JSON

A generated serializer is simply code that knows each field of a type and writes it. This program does the same job through record components, adding snake-case naming and handling lists, numbers, booleans and nested records. It stands in for the generated code; it is not what Micronaut produces, but the output matches what you would see from the API.

Java A record serializer with snake_case

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.

Reading JSON back

Deserialization is stricter than serialization. Unknown properties are ignored or rejected depending on configuration (jackson.deserialization.fail-on-unknown-properties), missing required values become null for objects and 0 for primitives unless validated, and a wrong type gives 400 Bad Request. Add @NotNull, @NotBlank and @Valid to catch missing values early, as covered in the validation lesson later in this course.

When a client sends malformed or incompatible JSON, Micronaut answers with 400 and a JSON error document with a message and the path of the failing property, for example Invalid JSON: Illegal unquoted character. Do not catch these yourself in each controller; one error handler can shape every error response.

Stand-in 2: binding JSON to a record with errors

This stand-in contains a very small JSON parser and a binder that fills a record from the parsed map. It reports a missing field or a wrong type with a precise message. It handles only a few types, which is enough to see how binding and error reporting relate.

Java Parsing and binding JSON

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.

What to remember

Mark types @Serdeable, expose DTO records, keep secrets out of JSON with @JsonIgnore, and let one global setting decide naming and null handling. The same serialization machinery powers the declarative client in the next lesson.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens if a response type is not annotated with @Serdeable (Micronaut Serialization)?

    Micronaut Serialization needs the opt-in so the processor can generate the code.
  2. 2. Which annotation keeps a password hash out of the JSON?

    @JsonIgnore excludes the property, though a separate response record is even safer.
  3. 3. How are java.time values such as LocalDate written by default?

    Dates and times are supported and use ISO-8601 text unless you change the format.
  4. 4. Why are separate request and response records recommended?

    DTOs decouple your public API from your entities and let input and output differ.

Summary

  • Micronaut Serialization generates serializers at compile time; opt in with @Serdeable.
  • Jackson annotations (@JsonProperty, @JsonIgnore, @JsonInclude, @JsonFormat) shape the JSON.
  • Global naming and inclusion rules live in application.yml.
  • Use @SerdeImport for third-party types, and records as DTOs.
  • Malformed or incompatible input gives 400; validate required fields.

Next: Declarative HTTP Clients