Registering subtypes without annotating the parent class, see this.
Implementation on SPI.
Registering modules.
ObjectMapper mapper = JsonMapper.builder()
.addModule(new SubtypesModule())
.build();
Ensure that the parent class has at least the JsonTypeInfo annotation.
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
public interface Parent {
}- add the
JacksonSubTypeannotation to your subclass. - provide a non-argument constructor (SPI requires it).
package org.example;
import tools.jackson.module.spisubtypes.JacksonSubType;
@JacksonSubType("first-child")
public class FirstChild {
private String foo;
// ...
public FirstChild() {
}
}SPI: Put the subclasses in the META-INF/services directory under the interface.
Example: META-INF/services/org.example.Parent
org.example.FirstChild
Alternatively, you can also use the auto-service to auto-generate these files:
package org.example;
import tools.jackson.module.spisubtypes.JacksonSubType;
import com.google.auto.service.AutoService;
@AutoService(Parent.class)
@JacksonSubType("first-child")
public class FirstChild {
private String foo;
// ...
public FirstChild() {
}
}Done, enjoy it.