Configuring Objectmapper in Spring

Configuring ObjectMapper in Spring

Using Spring Boot (1.2.4) and Jackson (2.4.6) the following annotation based configuration worked for me.

@Configuration
public class JacksonConfiguration {

@Bean
public ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, true);

return mapper;
}
}

How to Define a Custom Object Mapper In Spring Boot Without Impacting Default Object Mapper of Spring Boot?

The Spring Jackson auto configuration uses @ConditionalOnMissingBean to create the default ObjectMapper. This means it only creates it if there isn't an existing bean of the same type. So by creating your own ObjectMapper bean, the Spring auto config doesn't create one.

I think you have a couple of options:

  • If you need to control the behavior of the default Spring ObjectMapper, then you can use the spring.jackson.* properties to configure its behavior.
  • If you really need 2 ObjectMapper objects with different behavior, you'll have to create them both as beans, give them unique names, and mark one as @Primary to control when/where they are autowired.

How to override Jackson ObjectMapper configuration for Spring Cloud Stream?

As documented in discussion comments below and here, there is a bug in Spring Cloud Stream that it's not using the ObjectMapper from the Spring application context in places that it should.

Having said that, a workaround is to define your own Serde<> @Bean which calls the JsonSerde<> constructor that takes an ObjectMapper, which is injected from the app context. For example:

@Configuration
public class MyConfig {
@Bean
public Serde<SomeClass> someClassSerde(ObjectMapper jsonMapper) {
return new JsonSerde<SomeClass>(SomeClass.class, jsonMapper);
}
}

The downside to this workaround is that you have to do it for every target type that you want to serialize/deserialize in messages.

set Object Mapper SerializationFeature in spring configuration

You can use Jackson2ObjectMapperFactoryBean to configure ObjectMapper instance

Example

<property name="objectMapper">
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"
p:failOnEmptyBeans="false"
p:indentOutput="true">
<!-- Other properties -->
</bean>
</property>


Related Topics



Leave a reply



Submit