如何在 spring 中将对象序列化为 json ad hoc [英] How to serialize object to json ad hoc in spring
问题描述
我创建了一个 Spring 启动应用程序,将消息发送到 Kafka 队列(使用 spring 集成 kafka 支持).我想发送任意的 json 序列化对象.
I created a Spring boot application that sends messages to Kafka queues (using spring integrations kafka support). I want to send arbitrary json-serialized objects.
有没有办法在我的 Spring Boot 应用程序中获取/注入一个 json-de-/serializer?或者如何临时去/序列化一个对象?
Is there a way to get/inject a json-de-/serializer within my spring boot application? Or how to ad hoc de-/ serialize an object?
应用序列化的良好做法是什么?
what are good practices to apply serialization?
推荐答案
Apache Kafka 在其主题中存储和传输字节数组.它附带了许多内置(反)序列化程序,但不包括 JSON 序列化程序.幸运的是,Spring Kafka 框架包含一个支持包,其中包含一个 JSON(反)序列化程序,该程序在幕后使用 Jackson ObjectMapper.
您可以添加这样的配置文件
Apache Kafka stores and transports Byte arrays in its topics. It ships with a number of built in (de)serializers but a JSON one is not included. Luckily, the Spring Kafka framework includes a support package that contains a JSON (de)serializer that uses a Jackson ObjectMapper under the covers.
You can add a config file like this
@Configuration
public class KafkaConfiguration {
@Bean
public ConsumerFactory<String, Operation> consumerFactory(KafkaProperties kafkaProperties) {
return new DefaultKafkaConsumerFactory<>(kafkaProperties.buildConsumerProperties(), new StringDeserializer(), new JsonDeserializer<>(Operation.class));
}
@Bean
public ConcurrentKafkaListenerContainerFactory<String, Operation> kafkaListenerContainerFactory(ConsumerFactory<String, Operation> consumerFactory) {
ConcurrentKafkaListenerContainerFactory<String, Operation> factory = new ConcurrentKafkaListenerContainerFactory<>();
factory.setConsumerFactory(consumerFactory);
return factory;
}
}
将 Operation
替换为您要反序列化的类.
Replace Operation
with your class which you want to deserialize.
这篇关于如何在 spring 中将对象序列化为 json ad hoc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!