Spring @RequestBody包含不同类型的列表(但是相同的接口) [英] Spring @RequestBody containing a list of different types (but same interface)
本文介绍了Spring @RequestBody包含不同类型的列表(但是相同的接口)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个域类:
public class Zoo{
private List<Animal> animals;
....
其中Animal是具有不同实现的接口(Cat,Dog) )。假设我希望能够保存Zoo对象:
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) {
....
我希望发送一个json - 类似于:
and I want to send a json - something like :
{
animals:[
{type:'Cat', whiskers-length:'3'},
{type:'Dog', name:'Fancy'}
]
}
当键入=='Cat'时,如何告诉spring MVC将动物映射到Cat类型并将其映射到类型为=='狗'的狗类?
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'?
推荐答案
你应该使用Jackson注释 @JsonTypeInfo
和 @JsonSubTypes
实现多态json。注释在 Animal
基类上。
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 {
}
这篇关于Spring @RequestBody包含不同类型的列表(但是相同的接口)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文