[英]How to deserialize Json string from Kafka topic in spring boot
[英]Not able to Deserialize json string coming from kafka topic which has attributes in snake case
他
我無法反序列化來自 kafka 主題的 json 字符串。 屬性混合了蛇案例和駱駝案例結構,例如:輸入:
{
"event_type" : "ABC",
"user_id" : 1567221,
"name" : "HGHAAAB" //here no snake case
"user_contact" : "12345678",
"phoneNumber" : "91222"
}
現在我想在我這邊創建請求 DTO,如下所示:
public class KafkaRequest {
private String eventType;
private int userId;
private String name;
private String userContact;
private String phoneNumber;
//getters and setters
}
任何人都可以建議正確的方法嗎? 我嘗試創建 CustomNameStrategy 並使用 ObjectMapper.readValue() 反序列化,但它不起作用。
謝謝提前!!!
如果您使用的是jackson
,您可以使用@JsonProperty
6.1。 @JsonProperty
@JsonProperty("event_type")
private String eventType;
或者您可以將屬性PropertyNamingStrategy.SNAKE_CASE設置為ObjectMapper
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
您可以使用 GSON 有辦法定義字段名稱策略
Gson gson = new GsonBuilder().disableHtmlEscaping().setFieldNamingStrategy(FieldNamingPolicy.UPPER_CAMEL_CASE_WITH_SPACES).create();
甚至你也可以定義自定義
Gson gson = new GsonBuilder().disableHtmlEscaping().setFieldNamingStrategy(new FieldNamingStrategy() {
@Override
public String translateName(Field f) {
return f.getName().toLowerCase(); //or any logic
}
}).create();
對於 Producer,只需 StringSerializer 即可
properties.setProperty(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
properties.setProperty(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
假設您已經填充了 POJO 說 kafkaRequest 然后您可以發布
ProducerRecord producerRecord = new ProducerRecord<String, String>("topicName", null, gson.toJson(kafkaRequest));
在消費者端解析回 POJO
properties.setProperty("key.deserializer", StringDeserializer.class.getName());
properties.setProperty("value.deserializer", StringDeserializer.class.getName());
KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(properties);
while (true) {
ConsumerRecords<String, String> records = consumer.poll(100);
for (ConsumerRecord<String, String> record : records) {
KafkaRequest kafkaRequest = gson.fromJson(record.value(), KafkaRequest.class);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.