github linkedin
Customize Micronaut JSON serialization

or: why won’t Micronaut serialize my empty lists?

Micronaut omits fields which are null or empty in its JSON output.

For example, this code

class Dto {
    public List<String> foo;
    public Optional<String> bar;
    public String baz;

class HelloController {
    public Dto test() {
        Dto result = new Dto(); = Collections.emptyList(); = Optional.empty();
        result.baz = null;

        return result;

results in this JSON:


Micronaut not also omits null fields and empty Optional, but also empty collections. This is a bit surprising.

To disable this behaviour, put this in your application.yml:

  serialization-inclusion: NON_ABSENT # Omit null and Optional.empty(), but include empty collections
    indent-output: true # Pretty-print JSON

With this setting, the resulting JSON is

  "foo" : [ ]

If you also want to include null fields and empty Optional, set serializationInclusion to ALWAYS:

  "foo" : [ ],
  "bar" : null,
  "baz" : null

This behaviour is partly documented here.

Tags: java micronaut

Back to posts