AlejoDev
AlejoDev

Reputation: 3252

How to configure jackson non null globally in Spring Boot 1.5.9

I'm using a Spring Boot 1.5.9 and jackson 2.8.10. I would like to configure this @JsonInclude(Include.NON_EMPTY) annotation globally so that all the objects of my API are serialized following the rules of the annotation.

How I can get this?

I have tried to get through the application.properties file

spring.jackson.default-property-inclusion=non_null

and also through a configuration class:

@Primary
    @Bean
    public Jackson2ObjectMapperBuilder objectMapperBuilder() {
        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
        builder.serializationInclusion(JsonInclude.Include.NON_NULL);
        builder.serializationInclusion(JsonInclude.Include.NON_EMPTY);
        builder.failOnUnknownProperties(false);
        return builder;
    }

But none of this has an effect. It does not work

Does anyone know how to make this work?

Upvotes: 1

Views: 4263

Answers (1)

Karol Dowbecki
Karol Dowbecki

Reputation: 44942

Using spring.jackson.default-property-inclusion=non_null property is the best approach as it will be picked by Jackson2ObjectMapperBuilder object. This should ensure that it will be applied everywhere.

This approach works in 2.0.0. I tested 1.5.9, 1.5.10, and 1.5.11 and 1.5.12 but neither of them worked with a simple test like:

@Autowired 
private ObjectMapper objectMapper;

@Test
public void shouldOutputEmpty() {
  Map<String, Object> obj = new HashMap<>();
  obj.put("a", null);
  String result = objectMapper.writeValueAsString(obj);
  assertThat(result).isEqualTo("{}");
}

This is strange because Appendix A mentions this property. One way to resolve is to update Jackson to 2.9.X (Spring Boot 2.0.0 uses 2.9.4):

dependencyManagement {
  dependencies {
    dependency 'com.fasterxml.jackson.core:jackson-core:2.9.4'
    dependency 'com.fasterxml.jackson.core:jackson-databind:2.9.4'
    dependency 'com.fasterxml.jackson.core:jackson-annotations:2.9.4'
  }
}

Upvotes: 3

Related Questions