自定义对象Map器的问题

bjg7j2ky  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(496)

此问题已在此处找到答案

将objectmapper注入spring kafka序列化器/反序列化器(3个答案)
昨天关门了。
我正在尝试向kafka主题发送一些消息,我想定制jackson objectmapper来序列化我的 LocalDateTime 就像这样 2021-07-08T16:43:02Z 但这两者都不是

@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;
    }

}

还是这个

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

成功了,,
我总是在主题中收到一条消息,其中字段时间为

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

应用程序.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
...
t9eec4r0

t9eec4r01#

实际上,将objectmapper注入SpringKafka序列化器/反序列化器可以工作,但我没有使用公认的答案

@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()));
    }

}

相关问题