0

I have a hierarchy of messages. The topmost message in the hierarchy is defined with @JsonTypeInfo and @JsonSubTypes. The class is not under my control. I extended the hierarchy with my own message and to allow Jackson to deserialize my message, customized ObjectMapper. By debugging, I figured out that I need to register subtypes to the "jacksonObjectMapper" bean. So my code is as follows:

@Component
public class JacksonConfig implements BeanPostProcessor {

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (beanName.equals("jacksonObjectMapper")) {
            ((ObjectMapper) bean).registerSubtypes(new NamedType(ExtendedMessage.class, "ExtendedMessage"));
        }
        return bean;
    }
}

The solution works, but I'm afraid it's a workaround and it won't work after Spring update (e.g. the bean name changes). Is there a documented way to customize the ObjectMapper that is used to deserialize messages?

Andriy Simonov
  • 1,276
  • 1
  • 11
  • 19

1 Answers1

0

Construct the deserializer yourself and pass it into the consumer factory, via a constructor or setter.

https://docs.spring.io/spring-kafka/docs/current/reference/html/#prog-json

If you are using Boot's auto-configured factory, use something like this

@Bean
JsonDeserializer deser(ConsumerFactory<Object, Object> cf) {
     ...
     cf.setDeserializer(...);
}
Gary Russell
  • 166,535
  • 14
  • 146
  • 179