Skip to content
Advertisement

Jackson subtypes – how to specify a default

I want to do something like this with subtypes. I have 3 different types of objects:

JavaScript

value can either be a string or an object.

The corresponding Java classes are

JavaScript

I don’t mind having a discriminator inside Obj1 and Obj2, but there is no place for one when the value is just a string. Is there a way that I can set this up so that if the value is a string, it deserializes to ValueString, but if it is an object, it deserializes to the correct ValueObj1 or ValueObj2?

Advertisement

Answer

It can be easily done by creating a custom deserializer first:
p.s. I assumed that there’re only three types of objects as you posted.

JavaScript

Then simply annotate class Value with @JsonDeserialize as follows:

JavaScript

Finally, let Jackson do the rest for you:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement