Spring @RequestBody containing a list of different types (but same interface)
java, json, spring, spring-mvc
Solution
You should use the Jackson annotations `@JsonTypeInfo` and `@JsonSubTypes` to achieve polymorphic json. The annotations go on the `Animal` base class.
@JsonTypeInfo(use = Id.NAME, include = As.PROPERTY, property = "type")
@JsonSubTypes({@JsonSubTypes.Type(value = Dog.class, name = "Dog"),
@JsonSubTypes.Type(value = Cat.class, name = "Cat")})
public abstract class Animal {
}
Problem
Let's say that I have a domain class : ``` public class Zoo{ private List<Animal> animals; .... ``` where an Animal is an interface with different implementations (Cat,Dog). Let's say that I want to be able to save a Zoo object : ``` @RequestMapping(value = "/zoo", method = RequestMethod.POST) public @ResponseBody void save(@RequestBody Zoo zoo) { .... ``` and I want to send a json - something like : ``` { animals:[ {type:'Cat', whiskers-length:'3'}, {type:'Dog', name:'Fancy'} ] } ``` How can I tell spring MVC to map animal to Cat type when type=='Cat' and to map it to a Dog class when type=='Dog'?