4

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

2 Answers 2

4

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);
Sign up to request clarification or add additional context in comments.

2 Comments

a simple example will be nice
I get the error org.apache.kafka.common.errors.SerializationException: Can't convert value of class java.util.HashMap to class org.apache.kafka.common.serialization.ByteArraySerializer specified in value.serializer
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.