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

问题描述

假设我有三个班级。

public abstract class Animal {}

public class Cat extends Animal {}

public class Dog extends Animal {}

我可以做这样的事情?

输入:json,它是狗或猫

Input: a json which it is Dog or Cat

输出:狗/ 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;
}

更新:sry我忘记包含错误消息

Update: sry i forget to include the error message

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会自动转换为 Cat 对象,具体取决于json输入。

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

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

08-11 04:15