github linkedin
Customize Micronaut JSON serialization
2019-10-04

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;
}

@Controller
class HelloController {
    @Get
    public Dto test() {
        Dto result = new Dto();

        result.foo = Collections.emptyList();
        result.bar = 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:

jackson:
  serialization-inclusion: NON_ABSENT # Omit null and Optional.empty(), but include empty collections
  serialization:
    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