DEV Community

Mel
Mel

Posted on

Configure MappingJackson2MessageConverter's ObjectMapper

In our service, we are expecting a ZonedDateTime data type from a queue (AWS SQS) message (that is subscribed to a AWS SNS) to be mapped in our POJO.

I kept getting this error

Caused by: org.springframework.messaging.converter.MessageConversionException: Could not read JSON: Cannot construct instance of `java.time.ZonedDateTime` (no Creators, like default construct, exist): no String-argument constructor/factory method to deserialize from String value ('2020-09-07T18:02:51.099+0000')

I thought that the solution was to override the ObjectMapper to be able to register the module JavaTimeModule so the message could be deserialized.
The solution was right but it still didn't solve the error.
I came to a realization (by the help of my coworker) that since we're using Spring Cloud to receive the message from the queue, messages that are received are handled by MappingJackson2MessageConverter.
https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jms/support/converter/MappingJackson2MessageConverter.html

The solution was to configure the MappingJackson2MessageConverter's object mapper (see to it that your ObjectMapper has a JavaTimeModule), and set other configurations as well.

@Bean
public MappingJackson2MessageConverter mappingJackson2MessageConverter(ObjectMapper objectMapper) {
    MappingJackson2MessageConverter jacksonMessageConverter = new MappingJackson2MessageConverter();
    jacksonMessageConverter.setObjectMapper(objectMapper);
    jacksonMessageConverter.setSerializedPayloadClass(String.class);
    jacksonMessageConverter.setStrictContentTypeMatch(true);
    return jacksonMessageConverter;
}

Hope this post helped you in any way!

Top comments (0)