Jackson polymorphism: How to map multiple subtypes to the same class
jackson, java, json
Solution
Perhaps not by using annotations. Problems comes from the fact that such mapping would not work for serialization, and existing mapping does expect one-to-one (bijection) relationship. But you may want to file an RFE at jackson-databind issue tracker; adding support may be possible.
Problem
I'm using Jackson 1.9.x. Sticking with the Animals example, Here's what I'd like to do: Let's say I have an Animal class: ``` public class Animal { private String type; // accessors } public class Mammal extends Animal { private String diet; // accessors } public class Bird extends Animal { private boolean tropical; // accessors } ``` I would like to be able to do something like this (where I map a few subtypes to one class, and a few more to a different class): ``` @JsonTypeInfo(use = Id.NAME, include = As.PROPERTY, property = "type") @JsonSubTypes({@JsonSubTypes.Type(value = Mammal.class, name = "Dog"), @JsonSubTypes.Type(value = Mammal.class, name = "Cat"), @JsonSubTypes.Type(value = Bird.class, name = "Dodo"}, @JsonSubTypes.Type(value = Bird.class, name = "Cockatoo"}) public class Animal { } ``` What I'm seeing right now is that Jackson will only recognize the Dog-to-Mammal and the Dodo-to-Bird mapping. This is because StdSubtypeResolver._collectAndResolve() only allows the same class to get registered once (due to the implementation of NamedType.equals()). Is there a workaround to the issue I'm seeing?