首页 > 解决方案 > 如何从 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
        
    }

任何帮助表示赞赏!谢谢

标签: javajsonspringspring-bootweb

解决方案


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 
}

推荐阅读