作者热门文章
- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
假设我有三个类(class)。
public abstract class Animal {}
public class Cat extends Animal {}
public class Dog extends Animal {}
我可以这样做吗?
输入:一个 JSON,它是 Dog 或 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;
}
错误信息:
HTTP Status 500 - Request processing failed; nested exception isjava.lang.IllegalArgumentException: Type variable 'T' can not beresolved
最佳答案
我自己找到了答案,这里是引用链接。
我所做的是在抽象类之上添加了一些代码
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{}
然后在html中的json输入中,
var inputjson = {
"type":"cat",
//blablabla
};
提交json后,最后在 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;
}
在这种情况下,变量 tmp 会根据 json 输入自动转换为 Dog
或 Cat
对象。
关于json - Spring @ReponseBody @RequestBody 与抽象类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27170298/
假设我有三个类(class)。 public abstract class Animal {} public class Cat extends Animal {} public class Dog
我是一名优秀的程序员,十分优秀!