Search code examples
spring-kafkajackson-databind

How to customize Json(De)Serializer in Spring Kafka producer/consumer? (self response)


As Spring doc suggests here, you can customize the behaviour of Json(De)Serializer in Kafka with an ObjectMapper but it does not specify how.


Solution

  • It turns out that Json(De)Serializer has a constructor which takes an ObjectMapper as arg, so you can inject the bean like:

    @Bean 
    Deserializer jsonDeserializer(ObjectMapper objectMapper) {
        return new JsonDeserializer(objectMapper);
    }
    

    as stated here.

    Also, if you need to add trusted package, you need to:

    • pick an ObjectMapper from context, pass it to the bean of json serializer
    • in the @Bean method, add trusted package
    • pass this bean to factory to get the final consumer

    And the link above also mentions that if you use context properties to get the Json(De)Serializer, it is generated by Kafka, without being aware of any context.