My REST endpoint returns Response object containing Object field. Everything is fine with serialization but when I started to write client for this API I encountered an issue with deserialization. I made this example code based on some questions/articles about polymorphic serialization with Jackson. It demonstrates the issue.
@Data
abstract class Animal {
String name;
}
@Data
class Dog extends Animal {
boolean canBark;
}
@Data
class Cat extends Animal {
boolean canMeow;
}
@Data
public class Zoo {
private Object animals;
}
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "name", visible = true)
@JsonSubTypes({
@JsonSubTypes.Type(name = "dog", value = Dog.class),
@JsonSubTypes.Type(name = "cat", value = Cat.class)
})
public class Mixin {
}
public class Main {
private static final String JSON_STRING = "{\n"
+ " \"animals\": [\n"
+ " {\"name\": \"dog\"},\n"
+ " {\"name\": \"cat\"}\n"
+ " ]\n"
+ "}";
public static void main(String[] args) throws IOException {
ObjectMapper objectMapper = Jackson.newObjectMapper()
.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE)
.setDefaultPropertyInclusion(Include.NON_NULL);
objectMapper.addMixIn(Animal.class, Mixin.class);
Zoo zoo = objectMapper.readValue(JSON_STRING, Zoo.class);
for (Object animal : (Collection) zoo.getAnimals()) {
System.out.println(animal.getClass());
}
}
}
What I expect(and what I have with List<Animals>
as Zoo#animals type) in output:
class jackson.poly.Dog
class jackson.poly.Cat
What I have now with Object:
class java.util.LinkedHashMap
class java.util.LinkedHashMap
But I need to deserialize other types of objects besides list of animals. Help please!
I express sincere gratitude to all who participated. I decided to go with a little bit introspective approach and wrote custom deserializer that looks inside first object in list to figure out if it needs to deserialize this as List.
Maybe some checks are redundant. It works and it's all that matters :). Award goes to StephanSchlecht as author of most inspirational answer. Thanks again!