Skip to content
Advertisement

Spring with Jackson set JsonAutoDetect globally

In my spring boot web application, I want to serialize many different classes to JSON when I return them from the function of a request mapping. These classes only contain private fields without getters. In order for Jackson to serialize these private fields I can annotate all those classes with the following annotation, which works perfectly fine as expected.

JavaScript

But because want to serialize many different classes in that manner, I would like to declare that globally in my spring boot application. I have tried the following approaches to achieve this:

Set the field visibility in the used application.properties to any.

JavaScript

Customize the ObjectMapper using @Bean in the main class.

JavaScript

Customize the Jackson2ObjectMapperBuilder using @Bean in the main class.

JavaScript

Configure the Jackson2ObjectMapperBuilder using a configuration class.

JavaScript

But none of those approaches worked for me. It works perfectly fine if I use the @JsonAutoDetect annotation on every class I would like to serialize, but if I try to use one of those global implementations, I always get the following error:

JavaScript

I have no Idea what could cause this behaviour, or whether I had missed something crucial elsewhere, but all global approaches I found did not work. Nonetheless, I would still like to not annotate all individual classes or not to have to define thousands of getters in them.

Advertisement

Answer

The fact that all of the options that should work with Spring Boot don’t work lead to the conclusion that you must have (accidentally or deliberately) disabled the auto configuration of MVC and/or Jackson.

When you add a configuration class with @EnableWebMvc most of the web related auto configuration will backoff and use the defaults provided by Spring and what you provided. This will also make it so that those features will not work.

Removing that annotation and specifying the property in the application.properties should be enough to make it work.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement