'Kafka custom deserializer converting to Java object

I'm using Spring Kafka integration and I've my own value generic serializer/deserializer as shown below

Serializer:

public class KafkaSerializer<T> implements Serializer<T> {

  private ObjectMapper mapper;

  @Override
  public void close() {
  }

  @Override
  public void configure(final Map<String, ?> settings, final boolean isKey) {
    mapper = new ObjectMapper();
  }

  @Override
  public byte[] serialize(final String topic, final T object) {
    try {
      return mapper.writeValueAsBytes(object);
    } catch (final JsonProcessingException e) {
      throw new IllegalArgumentException(e);
    }
  }
}

Deserializer:

public class KafkaDeserializer<T> implements Deserializer<T> {

  private ObjectMapper mapper;

  @Override
  public void close() {
  }

  @Override
  public void configure(final Map<String, ?> settings, final boolean isKey) {
    mapper = new ObjectMapper();
  }

  @Override
  public T deserialize(final String topic, final byte[] bytes) {
    try {
      return mapper.readValue(bytes, new TypeReference<T>() {
      });
    } catch (final IOException e) {
      throw new IllegalArgumentException(e);
    }
  }
}

The serializer is working perfectly but when it comes to deserialization of values while consuming message I get a LinkedHashMap instead of desired object, please enlighten me where I'm mistaking, thanks in advance.



Solution 1:[1]

Some situations need be confirmed:

  1. your Serializer is works
  2. the Deserializer is just works but it returned a LinkedHashMap instead of a object that you expected, right? and you can't convert that LinkedHashMap to your object.

I find the question transfers to How to Convert/Cast a LinkedHashMap to a Object, and you used ObjectMapper. If all situations can be confirmed, I found here a good post may be answer your question Casting LinkedHashMap to Complex Object

mapper.convertValue(desiredObject, new TypeReference<type-of-desiredObject>() { })

ObjectMapper's API at [here](https://fasterxml.github.io/jackson-databind/javadoc/2.3.0/com/fasterxml/jackson/databind/ObjectMapper.html#convertValue(java.lang.Object, com.fasterxml.jackson.core.type.TypeReference))

And I hopes I don't missing your intention, and you can complement necessary situations, so someone or me can improve this answer.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community