Search code examples
genericsjacksonpolymorphism

Deserializing polymorphic type in Jackson using readValue with passed derived class


I have a method where I want to use Jackson to deserialize a value from the inherited class but not knowing which inherited class it is.

Using an example class structure and skeleton code to explain my issue:

public abstract class Vehicle {
  private String make; 
}

public class Car extends Vehicle { }

public class ProcessStuff {

  // how to construct parameter so I know what class to use, Vehicle<?>?
  private processThis(String jsonDataString, Vehicle<?> vehicle) {
    final ObjectMapper objectMapper = new ObjectMapper();
  
    // if knew class I could read like this
    // Car car = objectMapper.readValue(jsonDataString, new TypeReference<Car>() {}); 

    // how to readValue from unknown derived class? 
    // second parameter does not compile
    final Vehicle aVehicleInstance = objectMapper.readValue(jsonDataString, new vehicle);
  }
}

Calling processThis

  // or should I pass Car.class or what?
  processThis(jsonDataString, New Car());

Solution

  • I figured out a solution:

    public class ProcessStuff() {
    
      private processThis(String jsonDataString, Class myVehicleClass) {
        final ObjectMapper objectMapper = new ObjectMapper();
    
        final Vehicle aVehicleInstance = objectMapper.readValue(jsonDataString, new vehicle);
        Vehicle <?> aVehicleInstance = null;
        try {
            aVehicleInstance = (Vehicle <?>) objectMapper.readValue(jsonDataString, myVehicleClass);
        } catch (JsonProcessingException exception) {
           // log error
        }
      } 
    }
    

    Called by

    processThis(jsonDataString, Car.class);