Spring @ReponseBody @RequestBody with abstract class

后端 未结 1 812
小鲜肉
小鲜肉 2020-12-14 01:56

Suppose I have three classes.

public abstract class Animal {}

public class Cat extends Animal {}

public class Dog extends Animal {}

Can i

相关标签:
1条回答
  • 2020-12-14 02:26

    ref link

    I just found the answer myself and here is the reference link.

    What I have done is added some code above the abstract class

    import com.fasterxml.jackson.annotation.JsonSubTypes;
    import com.fasterxml.jackson.annotation.JsonTypeInfo;
    import com.fasterxml.jackson.annotation.JsonTypeInfo.*;
    
    @JsonTypeInfo(use = Id.NAME, include = As.PROPERTY, property = "type")
    @JsonSubTypes({
        @JsonSubTypes.Type(value = Cat.class, name = "cat"),
        @JsonSubTypes.Type(value = Dog.class, name = "dog")
    })
    public abstract class Animal{}
    

    Then in the json input in HTML,

    var inputjson = {
        "type":"cat",
        //blablabla
    };
    

    After submitting the json and finally in the controller,

    @RequestMapping(value = "/animal", method = RequestMethod.POST, produces = "application/json; charset=utf-8", consumes=MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody insertanimal(@RequestBody Animal tmp) {
        return tmp;
    }
    

    In this case variable tmp is automatically converted to a Dog or Cat object, depending on json input.

    0 讨论(0)
提交回复
热议问题