Spring @RequestBody 包含不同类型的列表(但接口相同) [英] Spring @RequestBody containing a list of different types (but same interface)

查看:60
本文介绍了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'}
        ]
    }

如何告诉 Spring MVC 在 type=='Cat' 时将动物映射到 Cat 类型,而在 type=='Dog' 时将其映射到 Dog 类?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆