0

I am tring produce some message to kafka topic and I want to customize the Jackson ObjectMapper to serialize my LocalDateTime as String like this 2021-07-08T16:43:02Z

But neither this

@Configuration
public class WebConfiguration {

    ...

    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new JavaTimeModule());
        mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        return mapper;
    }


}

or this

spring:
  jackson:
    serialization:
      write-dates-as-timestamps: false

has worked,

I get always in the topic a message with field time as

"time": [
    2021,
    7,
    8,
    10,
    46,
    29,
    598476000
]

application.yaml

spring:
  main:
    web-application-type: none

  kafka:
    bootstrap-servers: ${KAFKA_SERVERS}
    producer:
      key-serializer: org.apache.kafka.common.serialization.StringSerializer
      value-serializer: org.springframework.kafka.support.serializer.JsonSerializer
...
Hayi
  • 6,972
  • 26
  • 80
  • 139
  • 1
    Yes; when configuring the serializer via kafka properties, Kafka creates it, not Spring. See the answer to that question. – Gary Russell Jul 09 '21 at 13:13

1 Answers1

0

indeed this Inject ObjectMapper into Spring Kafka serialiser/deserialiser works but I didn't use the accepted answer

@Configuration
public class KafkaCustomizerConf implements DefaultKafkaProducerFactoryCustomizer {

    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new JavaTimeModule());
        mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        return mapper;
    }


    @Override
    public void customize(DefaultKafkaProducerFactory<?, ?> producerFactory) {
        producerFactory.setValueSerializer(new JsonSerializer<>(objectMapper()));
    }


}
Hayi
  • 6,972
  • 26
  • 80
  • 139