[英]How to deserialize Json string from Kafka topic in spring boot
I created a POJO to map a payload received from a Kafka topic.我创建了一个 POJO 来映射从 Kafka 主题收到的有效负载。 It works if the format of payload is:
如果有效负载的格式为:
{"payload":{"name":notification,"key":"2637","message":"This is a notif"}
When I produce this message of JSON string type.当我生成此 JSON 字符串类型的消息时。
"{\"payload\":{\"name\":\"notification\",\"key\":\"2637\",\"message\":\"This is a notif\"}"
It is throwing它在扔
Could not read JSON:Cannot construct instance of myfilename : no sting-argument constructor/factory method to deserialize from string value.
无法读取 JSON:无法构造 myfilename 的实例:没有从字符串值反序列化的带刺参数构造函数/工厂方法。
How to fix it?如何解决?
I think you just need to use a StringDeserializer if the message is just a String representing escaped JSON, and handle the message as a String.如果消息只是一个表示转义 JSON 的字符串,我认为您只需要使用 StringDeserializer,并将消息作为字符串处理。 I don't think you can automatically bind to a POJO because it is not an actual JSON object.
我认为您不能自动绑定到 POJO,因为它不是实际的 JSON 对象。
You could write a custom deserializer to convert the String then delegate to an ObjectMapper.您可以编写自定义反序列化器来转换字符串,然后委托给 ObjectMapper。
Your issue possibly could be resolved by using below setting in the mapper :您的问题可能可以通过在映射器中使用以下设置来解决:
mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
On the side note, if you are already using spring-kafka
, you can use the default JsonDesrializer
or a custom deserializer.另外,如果您已经在使用
spring-kafka
,则可以使用默认的JsonDesrializer
或自定义反序列化器。
consumerProps.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JsonDeserializer.class);
More documentations are available in the spring documentation更多文档可在spring 文档中找到
Another ref : Deserialize kafka messages in KafkaConsumer using springboot另一个参考: 使用 springboot 在 KafkaConsumer 中反序列化 kafka 消息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.