I'd like to deserialize an object from YAML with the following properties, using Jackson in a Spring Boot application:
- Abstract class
Vehicle
, implemented byBoat
andCar
- For simplicity, imagine both have a name, but only
Boat
has also aseaworthy
property, whileCar
has atop-speed
.
mode-of-transport:
type: boat
name: 'SS Boatface'
seaworthy: true
----
mode-of-transport:
type: car`
name: 'KITT'
top-speed: 123
This all works fine in my annotated subclasses using @JsonTypeInfo
and @JsonSubTypes
!
Now, I'd like to create a shorthand using only a String value, which should create a Car
by default with that name:
mode-of-transport: 'KITT'
I tried creating my own custom serializer, but got stuck on most of the relevant details. Please help me fill this in, if this is the right approach:
public class VehicleDeserializer extends StdDeserializer<Merger> {
/* Constructors here */
@Override
public Vehicle deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
if (/* it is an OBJECT */){
// Use the default polymorphic deserializer
} else if (/* it is a STRING */) {
Car car = new Car();
car.setName( /* the String value */ );
return car;
}
return ???; /* what to return here? */
}
}
I found these 2 answers for inspiration, but it looks like combining it with polymorphic types makes it more difficult: How do I call the default deserializer from a custom deserializer in Jackson and Deserialize to String or Object using Jackson
A few things are different than the solutions offered in those questions:
- I am processing YAML, not JSON. Not sure about the subtle differences there.
- I have no problem hardcoding the 'default' type for Strings inside my Deserializer, hopefully making it simpler.