java Spring @RequestBody 包含不同类型的列表(但接口相同)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17247189/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 01:27:04  来源:igfitidea点击:

Spring @RequestBody containing a list of different types (but same interface)

javajsonspringspring-mvc

提问by Viktor K.

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 :

其中 Animal 是具有不同实现(Cat、Dog)的接口。假设我希望能够保存 Zoo 对象:

    @RequestMapping(value = "/zoo", method = RequestMethod.POST)
    public @ResponseBody void save(@RequestBody Zoo zoo) {
    ....

and I want to send a json - something like :

我想发送一个 json - 类似于:

    {
        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'?

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

回答by nicholas.hauschild

You should use the Hymanson annotations @JsonTypeInfoand @JsonSubTypesto achieve polymorphic json. The annotations go on the Animalbase class.

您应该使用 Hymanson 注释@JsonTypeInfo@JsonSubTypes实现多态 json。注释在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 {

}

回答by Prancer

There is a simpler annotation out now:

现在有一个更简单的注释:

@JsonRootName("dog")
public class Dog extends Animal {...}

The reference to the annotation can be found on fasterxml.github

注释的参考可以在fasterxml.github找到