I have a kafka consumer which does the deserialization of JSON.
I get big messages like :
{
data1: [],
data2: ["content"],
data3: null,
data4: [],
data5: "foo",
data6: "",
data7: [""],
data8: [null],
...
dataX: []
}
with a lot of keys, where the values are null respective empty lists. I want handle only the keys, which does have values or lists with senseful content like data2 or data5 and ignore the others. Even with data6 (empty string) and data7 (list with empty string) I want stay. This shall pass.
I have this kafka consumer configuration.
private void configureAndInitConsumer() {
final Properties props = new Properties();
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
props.put(ConsumerConfig.GROUP_ID_CONFIG, consumerGroupId);
props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, autoCommit);
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, org.apache.kafka.connect.json.JsonDeserializer.class.getName());
props.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, maxPollRecords);
consumer = new KafkaConsumer<>(props);
}
I see, that here the org.apache.kafka.connect.json.JsonDeserializer is configured. But the config is for kafka consumer.
I can configure the deserializer by replacing the KafkaConsumer constructor.
JsonDeserializer<JsonNode> valueDeserializer = createCustomizedJsonDeserializer();
consumer = new KafkaConsumer<>(props, new StringDeserializer(), valueDeserializer);
and then I add the method
private JsonDeserializer<JsonNode> createCustomizedJsonDeserializer() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, false);
return new JsonDeserializer<>(JsonNode.class, objectMapper);
}
The hint for this I got from https://github.com/spring-projects/spring-kafka/issues/915
Is is possible that the Deserializer ignores the keys without values? (empty lists or null values)
I realized that the Deserializer intern has an object mapper. So I testest this:
public class ObjectMapperTest {
public static void main(String[] args) throws JsonMappingException, JsonProcessingException {
System.exit(new ObjectMapperTest().start());
}
private int start() throws JsonMappingException, JsonProcessingException {
String testJson = "{\"date1\":[],\"date2\":null,\"date3\":[null],\"date4\":[\"\"],\"date5\":[],\"date6\":\"\",\"date8\":\"foobar\"}";
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.disable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
JsonNode jn = objectMapper.readTree(testJson);
System.out.println(jn);
return 0;
}
}
I get this result:
{"date1":[],"date2":null,"date3":[null],"date4":[""],"date5":[],"date6":"","date8":"foobar"}
- I see there, that date2 is still there.