CodexBloom - Programming Q&A Platform

Java 11: how to to deserialize polymorphic types with Jackson using @JsonTypeInfo and @JsonSubTypes

👀 Views: 98 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-10
java jackson json deserialization polymorphism Java

Can someone help me understand I'm working on a Java 11 application using Jackson for JSON serialization and deserialization... My goal is to deserialize a list of objects that can be of different subtypes based on a type identifier in the JSON. I've annotated my classes with `@JsonTypeInfo` and `@JsonSubTypes`, but I'm working with an scenario where Jackson fails to recognize the subtype during deserialization. Here are the relevant class definitions: ```java import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type") @JsonSubTypes({ @JsonSubTypes.Type(value = Dog.class, name = "dog"), @JsonSubTypes.Type(value = Cat.class, name = "cat") }) public abstract class Animal { public String name; } public class Dog extends Animal { public String barkSound; } public class Cat extends Animal { public String meowSound; } } ``` And I am trying to deserialize the following JSON: ```json [ { "type": "dog", "name": "Buddy", "barkSound": "Woof" }, { "type": "cat", "name": "Whiskers", "meowSound": "Meow" } ] ``` However, when I run the following code: ```java import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.List; public class Main { public static void main(String[] args) throws Exception { String json = "[ { \"type\": \"dog\", \"name\": \"Buddy\", \"barkSound\": \"Woof\" }, { \"type\": \"cat\", \"name\": \"Whiskers\", \"meowSound\": \"Meow\" } ]"; ObjectMapper objectMapper = new ObjectMapper(); List<Animal> animals = objectMapper.readValue(json, new TypeReference<List<Animal>>() {}); System.out.println(animals); } } ``` I get the following behavior: ``` com.fasterxml.jackson.databind.JsonMappingException: want to construct instance of `Animal` (no Creator, default constructor, or bean property access) ``` I've confirmed that the `Animal` class is abstract and doesn't have a default constructor, but I thought the annotations would handle the deserialization of the subtypes. I've also tried making the `Animal` class non-abstract, but that didn't work either. Is there something I'm missing in my configuration? Any insights would be appreciated! The project is a CLI tool built with Java. Thanks, I really appreciate it! I'm developing on Linux with Java. Thanks in advance!