Him
I am not able to deserialize a json string coming from kafka topic. Attributes are in mix of snake case and camel case structure, for example: input:
{
"event_type" : "ABC",
"user_id" : 1567221,
"name" : "HGHAAAB" //here no snake case
"user_contact" : "12345678",
"phoneNumber" : "91222"
}
Now I want to create Request DTO on my side like below:
public class KafkaRequest {
private String eventType;
private int userId;
private String name;
private String userContact;
private String phoneNumber;
//getters and setters
}
Can any one suggest what should be the correct way? I tried creating CustomNameStrategy and deserializing with ObjectMapper.readValue() but it did not work.
Thanks is advance!!!
If you are using jackson
you can either use @JsonProperty
6.1. @JsonProperty
@JsonProperty("event_type")
private String eventType;
Or you can set property PropertyNamingStrategy.SNAKE_CASE to ObjectMapper
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
You can use GSON there are way to define field name strategy
Gson gson = new GsonBuilder().disableHtmlEscaping().setFieldNamingStrategy(FieldNamingPolicy.UPPER_CAMEL_CASE_WITH_SPACES).create();
or even u can define custom as well
Gson gson = new GsonBuilder().disableHtmlEscaping().setFieldNamingStrategy(new FieldNamingStrategy() {
@Override
public String translateName(Field f) {
return f.getName().toLowerCase(); //or any logic
}
}).create();
For Producer just StringSerializer will work
properties.setProperty(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
properties.setProperty(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
Assume you already have populated POJO say kafkaRequest then you can publish
ProducerRecord producerRecord = new ProducerRecord<String, String>("topicName", null, gson.toJson(kafkaRequest));
On Consumer side parse back to 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);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.