自定义对象映射器的问题 [英] Issue with customizing object mapper

查看:54
本文介绍了自定义对象映射器的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试生成一些消息到Kafka主题,我想自定义Jackson对象映射器以将我的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
...

推荐答案

这个Inject ObjectMapper into Spring Kafka serialiser/deserialiser确实有效,但我没有使用可接受的答案

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


}

这篇关于自定义对象映射器的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆