自定义对象映射器的问题
本教程将介绍自定义对象映射器的问题的处理方法,这篇教程是从别的地方看到的,然后加了一些国外程序员的疑问与解答,希望能对你有所帮助,好了,下面开始学习吧。
问题描述
我正在尝试生成一些消息到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()));
}
}
好了关于自定义对象映射器的问题的教程就到这里就结束了,希望趣模板源码网找到的这篇技术文章能帮助到大家,更多技术教程可以在站内搜索。