How to serialize object to json ad hoc in spring

2019-08-24 17:50发布

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.

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?

1条回答
手持菜刀,她持情操
2楼-- · 2019-08-24 18:11

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

Replace Operation with your class which you want to deserialize.

查看更多
登录 后发表回答