Nderim Bytyqi
Nderim Bytyqi

Reputation: 151

Spring Boot: Java 8 date/time type `java.time.OffsetDateTime` not supported by default

I have added the JavaTimeModule but still not able to get OffsetDateTime working on getting some data from RethinkDB @Configuration public class JacksonOffsetDateTimeMapper{

@Bean
@Primary
public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
    return builder.build()
            .registerModule(new JavaTimeModule());
}

}

Gradle dependencies for jackson: implementation group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.13.1'

implementation 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310'

implementation group: 'com.fasterxml.jackson.module', name: 'jackson-module-parameter-names', version: '2.13.1'

Upvotes: 15

Views: 24667

Answers (1)

Guilherme Pisco
Guilherme Pisco

Reputation: 81

Objects which are not manage by Spring and use "new ObjectMapper()" instead of autowiring it, will still face that issue. I was facing this issue while configuring a MappingJackson2MessageConverter to use with JMS, so in this case I had to set the ObjectMapper explicitly to the MappingJackson2MessageConverter object, as shown below.

    @Bean
    public MessageConverter messageConverter(){
        MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();

        converter.setTargetType(MessageType.TEXT);
        converter.setTypeIdPropertyName("_type");
        converter.setObjectMapper(objectMapper());
        return converter;
    }

    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new JavaTimeModule());
        return objectMapper;
    }

Additionally, we can also add the @Bean annotation on top of the objectMapper method, this way Spring managed objects will use this mapper instead.

In case there is already an ObjectMapper managed by Spring, we can just inject the ObjectMapper in the messageConvert, like below.

@Bean
public MessageConverter messageConverter(ObjectMapper objectMapper) 
{
   MappingJackson2MessageConverter converter = new 
   MappingJackson2MessageConverter();

   converter.setTargetType(MessageType.TEXT);
   converter.setTypeIdPropertyName("_type");
   converter.setObjectMapper(objectMapper);
   return converter;
}

Upvotes: 5

Related Questions