Manish Kumar
Manish Kumar

Reputation: 10482

Apache kafka sending java object failed

I have this object

       HashMap message = new HashMap();
       message.put("x", "xxxxx");
       message.put("y", "yyyyy");
       message.put("z", 100);

       ProducerRecord producerRecord = new ProducerRecord(topic, message);
       producer.send(producerRecord); 

I am getting

Exception in thread "main" org.apache.kafka.common.errors.SerializationException: Can't convert value of class java.util.HashMap to class org.apache.kafka.common.serialization.StringSerializer specified in value.serializer

Upvotes: 4

Views: 11422

Answers (2)

sarjit07
sarjit07

Reputation: 10559

You can convert the Hashmap into json and use JsonSerializer as

private void configureProducer() {
    Properties props = new Properties();
    props.put("key.serializer", StringSerializer.class.getName());
    props.put("value.serializer", JsonSerializer.class.getName());
    producer = new KafkaProducer<String, String>(props);
}

Or You can also use ByteArraySerializer. Refer this

Upvotes: 1

Nikem
Nikem

Reputation: 5776

You have to provide Kafka with a way how to convert you messages, in this case HashMap, into binary form. From the Kafka documentation:

The key.serializer and value.serializer instruct how to turn the key and value objects the user provides with their ProducerRecord into bytes. You can use the included ByteArraySerializer or StringSerializer for simple string or byte types.

The example of usage:

 Properties props = new Properties();
 props.put("key.serializer", "YourImplementation");
 props.put("value.serializer", "YourImplementation");

 Producer<String, HashMap> producer = new KafkaProducer<>(props);

Upvotes: 4

Related Questions