在Java Spring Boot中接收继承的对象时,我遇到一个小问题。
class AbstractEntity{
String type;
Integer age;
}
class Animal extends AbstractEntity{
String legs;
}
class Bird extends AbstractEntity{
String flySpeed;
}
class Human extends AbstractEntity{
String firstname;
String lastname;
}
Human
,Bird
并Animal
从被继承AbstractEntity
。现在,我从前端收到一个人类物体。我需要从中识别对象type
{
type: "Human",
age:30;
firstname:"John",
lastname: "Smith"
}
目前,我正在使用地图来识别
public void save(@RequestBody Map entity){
if(entity.get("type").equalsIgnoreCase("Human")){
Human h=new Human(entity.get("type"),entity.get("age"),entity.get("firstname"),entity.get("lastname"))
}
// same for Animal and bird
}
我无法在不知道控制器类型的情况下指定对象。如果我使用AbstractEntity
like收到对象,@RequestBody AbstractEntity entity
则子字段将丢失。有没有比使用更简单,更好的方法Map
?
提前致谢
我建议您探索Jackson批注@JsonTypeInfo
,@JsonSubTypes
以及@JsonTypeName
。
它将类似于:
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME,
include = As.PROPERTY, property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(value = Animal.class, name = "animal"),
@JsonSubTypes.Type(value = Bird.class, name = "bird"),
@JsonSubTypes.Type(value = Human.class, name = "human")
})
class AbstractEntity {
}
@JsonTypeName("animal")
class Animal extends AbstractEntity {
}
@JsonTypeName("bird")
class Bird extends AbstractEntity {
}
@JsonTypeName("human")
class Human extends AbstractEntity {
}
这只是一个基本示例,@JsonTypeName
如果我没有记错的话,还可以使用其他具有相同注释的方法,而无需定义。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句