gpt4 book ai didi

json - Spring @ReponseBody @RequestBody 与抽象类

转载 作者:IT老高 更新时间:2023-10-28 13:50:43 24 4
gpt4 key购买 nike

假设我有三个类(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

最佳答案

ref link

我自己找到了答案,这里是引用链接。

我所做的是在抽象类之上添加了一些代码

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 输入自动转换为 DogCat 对象。

关于json - Spring @ReponseBody @RequestBody 与抽象类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27170298/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com