Java 17 - Difficulty with Custom Object Serialization in Jackson with Polymorphic Types
I'm sure I'm missing something obvious here, but I'm collaborating on a project where Hey everyone, I'm running into an issue that's driving me crazy... Quick question that's been bugging me - I'm working with an scenario when trying to serialize and deserialize polymorphic types using Jackson in my Java 17 application. I have a base class `Animal` and two subclasses `Dog` and `Cat`. While I can successfully serialize and deserialize instances of `Dog` and `Cat`, I'm getting a `JsonMappingException` when I try to deserialize a list of `Animal` objects that includes both types. Here's the relevant code: ```java import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.List; @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") @JsonSubTypes({ @JsonSubTypes.Type(value = Dog.class, name = "dog"), @JsonSubTypes.Type(value = Cat.class, name = "cat") }) abstract class Animal { public String name; } class Dog extends Animal { public String bark; } class Cat extends Animal { public String meow; } public class Main { public static void main(String[] args) { ObjectMapper objectMapper = new ObjectMapper(); String json = "[{'type':'dog', 'name':'Rex', 'bark':'Woof'}, {'type':'cat', 'name':'Whiskers', 'meow':'Meow'}]"; try { List<Animal> animals = objectMapper.readValue(json, objectMapper.getTypeFactory().constructCollectionType(List.class, Animal.class)); } catch (JsonProcessingException e) { e.printStackTrace(); } } } ``` The behavior message I receive is: ``` com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class Animal] ``` This indicates that Jackson is unable to determine how to create an instance of the `Animal` class during deserialization. I've tried adding a no-argument constructor to the `Animal` class, but it hasn't resolved the scenario. I also ensured that I'm using the latest version of Jackson (2.13.0). What can I do to successfully deserialize a list of `Animal` objects with polymorphic types? What am I doing wrong? The stack includes Java and several other technologies. I'm coming from a different tech stack and learning Java. What am I doing wrong? My development environment is Ubuntu 20.04. Could this be a known issue?