1

In my Spring Boot/Kotlin project, I am trying to get the JSON converter to ignore null values in my rest controller responses.

I've tried setting the following in my application.yml:

spring:
    jackson:
        default-property-inclusion: non_null

I've also tried providing a @Bean of type Jackson2ObjectMapperBuilder and @ObjectMapper configured with .serializationInclusion(JsonInclude.Include.NON_NULL) but it's still serializing all the null properties.

Using Spring Boot 2.3.0, Kotlin 1.3.72, AdoptOpenJDK 13

António Ribeiro
  • 4,129
  • 5
  • 32
  • 49
MorganP
  • 183
  • 3
  • 11

1 Answers1

6

Well, I found the problem by creating a new project from scratch and adding pieces from the current one until I got the aberrant behavior.

Turns out the problem was in a class used to add CORS mappings:

@EnableWebMVC
@Configuration
class WebConfiguration : WebMvcConfigurer {
    override fun addCorsMappings(registry: CorsRegistry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
    }
}

I think I added @EnableWebMVC as seen in an example, but the class is not in the same part of the class hierarchy as the @RESTController classes, so it looks like that's why the object mapper configuration wasn't being applied. I don't know enough about the internal wiring of Spring/Boot to tell you why.

Once I removed @EnableWebMVC and allowed Spring Boot to add it to the application class through Autoconfiguration, it worked as expected...

MorganP
  • 183
  • 3
  • 11
  • 1
    Thank you for this!! Was about to do the same (start from scratch), but found your answer just in time! For me it was the `@EnableWebFlux` annotation that did it, but the result was the same. But how did you manage CORS then? – Terje Andersen Nov 11 '20 at 13:06
  • Man I have read tons and tons of tutorials how to set the `default-property-inclusion` but none of them worked because of that annotation. I'll try to find the tutorial from which I configured the CORS and leave a comment there to prevent future headaches for developers. Huge tanks to you, have my upvote! – aBnormaLz Jan 26 '21 at 13:47
  • @TerjeAndersen I just removed the `@EnableWebMVC` annotation and everything worked fine. The configuration class that registered the CORS mappings still works. The annotation enables a bunch of default settings for web mvc but it's not necessary in order to use `@RestController`s, etc. – MorganP Jun 18 '21 at 23:20
  • thank you! be nice to know _why_ it works – Rhubarb Dec 04 '21 at 19:44