How can I specify the second parameter in ObjectMapper based on a variable in Java?



I have a use case where I am consuming from multiple topics and based on the topic I have to create an object from a String. I have around 25 topics leading to 25 kinds of objects. So, instead of using a bunch of if-else, I want to use a map where the key will be the topic name. So, instead of doing this,

if(topic.equals("testTopic") {

  Event event = mapper.readValue(strMessage, TestEvent.class);

}

I want to do this

Event event = mapper.readValue(strMessage, map.get(topic)); 

Event is an interface implemented by all the classes, topic will store the topic name.

This is how I am creating ObjectMapper –

ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

How can I achieve this? Thanks in advance

Answer

Your map will contain topicNames and what class they should be mapped to. All classes implement Event.class

public class TestEvent implements Event {
}

 Map<String, Class<?extends Event>> mappings = new HashMap<>();
 mappings.put("testTopic", TestEvent.class);

The extends keyword may be used to qualify that to “any class which extends/implements Event

 Event testEvent = mapper.readValue("messagePayloadJSON", mappings.get("testTopic"));


Source: stackoverflow