0
votes

In a Spring Boot/Spring Cloud Stream application, we're using the Kafka binder. I've noticed that when deserializing Kafka messages that include a ZonedDateTime property, Jackson is automatically changing the time zone (to UTC) even when the serialized form includes time zone (eg, 20210101084239+0200). After some research, I discovered this is a default deserialization feature that can be disabled, so I added the following in one of my @Configuration classes:

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer objectMapperCustomizer() {
        return builder ->  {
            builder.featuresToDisable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
            //... other custom config...
        };

But that doesn't work, presumably because the ObjectMapper that Spring Cloud Stream (or the Kafka binder) uses is not constructed from the Jackson2ObjectMapperBuilder that's configured in the application context :-(.

After some more research, I found someone claiming that it was necessary to override Spring Messaging's MappingJackson2MessageConverter since it creates its own ObjectMapper. So I added this:

    @Bean
    public MappingJackson2MessageConverter springMessagingJacksonConverter() {
        MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
        converter.getObjectMapper().configure(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE, false);

        return converter;
    }

Unfortunately, that still didn't work. I still am getting ZonedDateTime objects deserialized ignoring the time zone info in the JSON values.

So what bean creates the ObjectMapper used by Spring Cloud Stream Kafka binder, and how can I customize its configuration?

1

1 Answers

0
votes

please see spring boot reference

If you want to replace the default ObjectMapper completely, either define a @Bean of that type and mark it as @Primary or, if you prefer the builder-based approach, define a Jackson2ObjectMapperBuilder @Bean. Note that, in either case, doing so disables all auto-configuration of the ObjectMapper.