Search code examples
javajacksonpojo

Deserialize message from JSON to POJO using Jackson


How would you deserialize a JSON document to a POJO using Jackson if you didn't know exactly what type of POJO to use without inspecting the message. Is there a way to register a set of POJOs with Jackson so it can select one based on the message?

The scenario I'm trying to solve is receiving JSON messages over the wire and deserializing to one of several POJOs based on the content of the message.


Solution

  • I'm not aware of a mechanism that you are describing. I think you will have to inspect the json yourself:

        Map<String, Class<?>> myTypes = ... 
        String json = ...
        JsonNode node = mapper.readTree(json);
        String type = node.get("type").getTextValue();
        Object myobject = mapper.readValue(json, myTypes.get(type));
    

    If you don't have a type field you will have to inspect the fields in the JsonNode in order to resolve the type.