java - 如何从 Json 中知道 SpringBoot 中的对象是哪个类?
问题描述
我在请求正文中有以下 JSON 对象:
JSON
{
"nombre": "example",
"number": 100,
"listOfMeasurables":{
"measurableOne":{
"positionOne":[0,3,0],
"positionTwo":[0,3,0]
},
"measurableTwo":{
"positionOne":[0,3]
}
}
}
现在我有了抽象类 Measurable,以及扩展 Measurable 的 MeasurableOne、MeasurableTwo 和 MeasurableThree。
可衡量的
public abstract class Measurable {
public abstract String getType();
}
可测量的
public class MeasurableOne extends Measurable {
protected int [] positionOne;
protected int [] positionTwo;
public MeasurableOne(int [] positionOne, int [] positionTwo) {
this.positionOne = positionOne;
this.positionTwo = positionTwo;
}
@Override
public String getType() {
return "MeasurableOne";
}
}
可测量二
public class MeasurableTwo extends Measurable {
protected int [] positionOne;
public MeasurableTwo(int [] positionOne) {
this.positionOne = positionOne;
}
@Override
public String getType() {
return "MeasurableTwo";
}
}
可测量的三
public class MeasurableThree extends Measurable {
protected int [] positionOne;
protected int [] positionTwo;
protected int [] positionThree;
public MeasurableThree(int [] positionOne, int [] positionTwo, int [] positionThree) {
this.positionOne = positionOne;
this.positionTwo = positionTwo;
this.positionThree = positionThree;
}
@Override
public String getType() {
return "MeasurableThree";
}
}
现在,我有一个控制器,它将接收这个 json。listOfMeasurables 数组可以包含 measurableOne、measurableTwo、measurableThree、1、2 或 3 个,顺序不限。我怎样才能让控制器知道可测量的类型以创建该对象?
@PostMapping(path = "/createActivity")
public ResponseEntity<String> createActivity(@RequestBody Activity activity) { ->> HERE
}
任何帮助表示赞赏!谢谢
解决方案
你Activity
可以用下面的代码定义,杰克逊会处理它
public class activity{
private String nombre;
private Integer number;
private ListOfMeasurables listOfMeasurables;
// getter and setter
}
public class ListOfMeasurables {
private MeasurableOne measurableOne;
private MeasurableTwo measurableTwo;
private MeasurableThree measurableThree;
// getter and setter
}
推荐阅读
- python - 如何在绘图中添加小时、分钟、日和月计数?
- json - JAX-RS Json 响应在一行中
- android - 当他不得不写他的名字时,如何检查用户是否没有在edittext中写数字或标点符号
- java - 如何为开源制作自己的 Maven 存储库和依赖项?
- reactjs - Webpack、babel 和 react:从生产构建中删除某些类名
- language-agnostic - 在不实际将地址传递给函数的情况下如何实现“按引用传递”?
- postgresql - 如何在 postgresql 中声明一个变量 INTERVAL?
- jsf - 更改 tabview 上的选项卡并刷新页面时,Bean 丢失了它们的对象值
- python - 如何查询 Haystack 以获得相似的项目
- android - 如何使recyclview单元格的可点击设置为假