Spring @ReponseBody @RequestBody 与抽象类 [英] Spring @ReponseBody @RequestBody with abstract class

查看:58
本文介绍了Spring @ReponseBody @RequestBody 与抽象类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有三个班级.

public abstract class Animal {}

public class Cat extends Animal {}

public class Dog extends Animal {}

我可以做这样的事情吗?

Can I do something like this?

输入:一个 JSON,它是 Dog 或 Cat

Input: a JSON which it is Dog or Cat

输出:狗/猫取决于输入对象类型

Output: a dog/cat depends on input object type

我不明白为什么下面的代码不起作用.或者我应该使用两种不同的方法来处理新的狗和猫?

I don't understand why the following code doesn't 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;
}

错误信息:

HTTP 状态 500 - 请求处理失败;嵌套异常是java.lang.IllegalArgumentException: 类型变量 'T' 不能是已解决

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

推荐答案

参考链接

我自己刚刚找到了答案,这里是参考链接.

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{}

然后在html中的json输入中,

Then in the json input in HTML,

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

提交json后,最后在控制器中,

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;
}

在这种情况下,变量 tmp 会自动转换为 DogCat 对象,具体取决于 json 输入.

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

这篇关于Spring @ReponseBody @RequestBody 与抽象类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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