如何从Json中知道对象在SpringBoot中属于哪个类



我在请求的主体中有以下JSON对象:

JSON

{
"nombre": "example",
"number": 100,
"listOfMeasurables":{
"measurableOne":{
"positionOne":[0,3,0],
"positionTwo":[0,3,0]
},
"measurableTwo":{
"positionOne":[0,3]
}
}
}

现在我有抽象的类Measureable,以及扩展Measureable的MeasureableOne、MeasureableTwo和MeasureableThree。

可测量

public abstract class Measurable {
public abstract String getType();

}

MeasureableOne

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

MeasureableTwo

public class MeasurableTwo extends Measurable {
protected int [] positionOne;

public MeasurableTwo(int [] positionOne) {
this.positionOne = positionOne;
}

@Override
public String getType() {
return "MeasurableTwo";
}
}

MeasureableThree

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。listOfMeasureables数组可以按任何顺序包含measureableOne、measureableTwo、measurebleThree、1、2或3。我如何让控制器知道可测量值是哪种类型,以便创建该对象?

@PostMapping(path = "/createActivity")
public ResponseEntity<String> createActivity(@RequestBody Activity activity) { ->> HERE

}

感谢您的帮助!感谢

您的Activity可以用以下代码定义,jackson将处理它

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 
}

最新更新