Java – polymorphism using Jackson to add subtype information at run time
I'm using Jackson to ungroup polymorphic types from JSON I use @ jsontypeinfo, @ jsonsubtypes and @ jsontypename annotations similar to example 4 in this post My problem is that now I need someone else to extend my code and add class 3: the public class duck extends the original version of animal's code base How can I (or someone else) add subtype information without modifying the source code (comments) of the public abstract animal class?
to update:
I was forced to use @ jsontypename to solve the change of POJO version For example:
package my.zoo;
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,include = JsonTypeInfo.As.PROPERTY,property = "type")
@JsonSubTypes({
@Type(value = Cat.class,name = "my.zoo.cat@1.0"),@Type(value = Dog.class,name = "my.zoo.dog@1.0"),@Type(value = Catv2.class,name = "my.zoo.cat@2.0")})
public abstract class Animal {
...
}
@JsonTypeName("my.zoo.cat@1.0")
public class Cat extends Animal {
...
}
@JsonTypeName("my.zoo.cat@2.0")
public class Catv2 extends Animal {
...
}
@JsonTypeName("my.zoo.dog@1.0")
public class Dog extends Animal {
...
}
// in another java package/project
package another.zoo;
import my.zoo.*;
@JsonTypeName("my.zoo.dog@2.0")
public class Dogv2 extends Animal {
...
}
The problem I'm facing now is that I can't ungroup without adding @ type, which has the type name "my. Zoo dog@2.0 ”JSON (value = other. Zoo. Dogv2. Class, name = "my. Zoo. Dog @ 2.0")}) to the animal class. Therefore, it is obviously impossible to perform this operation with annotations. Is there any way to perform this operation at runtime?
Update 2:
I just found that this so question has the same / similar use cases My concern is that using annotations will prevent people from extending / implementing your base class / interface I want a way to maintain the extensibility of my base class / interface and ensure that my (UN) marshalling logic will be applicable to specific types in the future
Solution
I finally used the reflections library to find all subtypes of the animal class and used mapper The registersubtypes (class ... Classes) method registers jsonsubtypes
