Springboot中多层object嵌套转换类的处理方法?

当springboot写后端接口时需要传入一个多层嵌套的大类UpdateAll(或者object)时,需要进行每一层object到类的转化,传入的前端参数形式为:

{
"before":{
"country": "中国",
"nation": "汉族",
"csplace": "北京"
},
"now":{
"country": "美国",
"nation": "汉族",
"csplace": "甘肃"
},"others":
{
"cUpdateOperate": "2",
"cUpdateType": "0",
"cUpdateOperateId": "yanjiangyi"
}
}

处理方法:

1、定义第一层大类UpdateAll()

@Data
@TableName("TABLE_UPDATE")
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@ApiModel(value="TABLE_UPDATE对象", description="basicinformation")
public class UpdateAll {
@ApiModelProperty("修改之前的信息")
private Object before; #对于第一层大类中包含的后续不确定具体属性字段的第二层类,我们需要定义为object

@ApiModelProperty("修改之后的信息")
private Object now;

@ApiModelProperty("其余信息")
private UpdateOthers others; #对于第一层大类中包含的后续确定具体字段的第二层类,我们需要定义为具体类名即可

    public UpdateAll(){}    //添加无参数构造函数,一定不要忘记
}
2、将不同的第二层类或者object对象根据类型都需要统一转化为具体类
(1)object的转化方式:
//        // 将传过来的before,now和othes三个object转为大类
// String objectstring = JSONArray.toJSONString(object);
// UpdateAll updateAll = JSONObject.parseObject(objectstring, UpdateAll.class);
String before =  JSONArray.toJSONString(updateAll.getBefore());
UpdateBasicInformation updatebefore = JSONObject.parseObject(before, UpdateBasicInformation.class)
String now =  JSONArray.toJSONString(updateAll.getNow());
UpdateBasicInformation updatenow = JSONObject.parseObject(now, UpdateBasicInformation.class);
(2)具体类的转化方式:
UpdateOthers updateOthers=updateAll.getOthers();   //直接利用get方法的方式获得的直接就是类

3、springboot后端接口传入的时候需要定义为具体的updateALL大类,用具体类的方式进行传参(也可以使用object的方式传参,之后进行转换)
@AutoLog(value = "个人档案信息编辑")
@ApiOperation(value = "个人档案信息编辑", notes = "个人档案信息编辑")
@PostMapping(value = "/save1")
public Result<Object> save(@RequestBody UpdateAll updateAll) {

Result<Object> result = new Result<Object>();

// // 将传过来的before,now和othes三个object转为大类
// String objectstring = JSONArray.toJSONString(object);
// UpdateAll updateAll = JSONObject.parseObject(objectstring, UpdateAll.class);

// String others = JSONArray.toJSONString(updateAll.getOthers());
// UpdateOthers updateOthers = JSONObject.parseObject(others, UpdateOthers.class);
// UpdateOthers updateOthers = (UpdateOthers)updateAll.getOthers(); 强制转化类的方式,一般不推荐使用,可能存在问题。
 
posted @ 2021-09-08 11:07  The-Chosen-One  阅读(681)  评论(0编辑  收藏  举报