如何在春季将对象序列化为json ad hoc [英] How to serialize object to json ad hoc in spring

查看:105
本文介绍了如何在春季将对象序列化为json ad hoc的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个Spring引导应用程序,该应用程序将消息发送到Kafka队列(使用Spring Integrations 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在其主题中存储和传输Byte数组.它附带了许多内置的(反)序列化器,但不包括JSON.幸运的是,Spring Kafka框架包括一个支持包,其中包含一个JSON(反序列化器),该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.

这篇关于如何在春季将对象序列化为json ad hoc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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