Spring @ReponseBody @RequestBody with abstract class

穿精又带淫゛_ 提交于 2019-12-17 15:48:10

问题


Suppose I have three classes.

public abstract class Animal {}

public class Cat extends Animal {}

public class Dog extends Animal {}

Can i do something like this?

Input: a json which it is Dog or Cat

Output: a dog/cat depends on input object type

I dont understand why the following code doesnt work. Or should I use two separate methods to handle new dog and cat?

@RequestMapping(value = "/animal", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
private @ResponseBody <T extends Animal>T insertAnimal(@RequestBody T animal) {
    return animal;
}

Update: sry i forget to include the error message

HTTP Status 500 - Request processing failed; nested exception is java.lang.IllegalArgumentException: Type variable 'T' can not be resolved


回答1:


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.



来源:https://stackoverflow.com/questions/27170298/spring-reponsebody-requestbody-with-abstract-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!