假设我有一个域类:
public class Zoo{ private List<Animal> animals; ....
其中Animal是具有不同实现(Cat,Dog)的接口。假设我希望能够保存Zoo对象:
@RequestMapping(value = "/zoo", method = RequestMethod.POST) public @ResponseBody void save(@RequestBody Zoo zoo) { ....
我想发送一个json-类似:
{ animals:[ {type:'Cat', whiskers-length:'3'}, {type:'Dog', name:'Fancy'} ] }
我如何告诉Spring MVC在type ==’Cat’时将动物映射到Cat类型,在type ==’Dog’时将其映射到Dog类?
您应该使用Jackson注释@JsonTypeInfo并@JsonSubTypes实现多态json。注释在Animal基类上。
@JsonTypeInfo
@JsonSubTypes
Animal
@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 { }