即将被解析的json
{
"collection": {
"templates": [{
"data": [{
"name": "plantCode",
"value": "MSHG_KFXHS02"
}, {
"name": "details",
"value": [{
"plantMedicamentId": 182,
"plantCode": "MSHG_KFXHS02",
"medicamentCode": "MTRL005",
"medicamentName": "工业硫酸",
"presetsNumber": "21",
"dimension": "kg",
"creatUser": "mshg",
"creatTime": "2024-07-10 16:02:36",
"updateUser": "",
"updateTime": ""
}]
}]
}]
}
}
controller层,通过@RequestBody 正常接收
@SneakyThrows
@Log
@ApiOperation(value = "新增", notes = "装置药剂关联表数据")
@PostMapping(value = "/addDemo")
public void addDemo(@RequestBody String savePlantMedicamentInfo)
throws Exception {
plantMedicamentService.addDemoInfo(savePlantMedicamentInfo);
}
service 手动解析
这块主要看怎么一层一层的解析数据并完成转换
public void addDemoInfo(String savePlantMedicamentInfo) {
Gson gson = new Gson();
JsonElement root = gson.fromJson(savePlantMedicamentInfo, JsonElement.class);
JsonObject collectionObj = root.getAsJsonObject().getAsJsonObject("collection");
JsonArray templatesArray = collectionObj.getAsJsonArray("templates");
JsonArray dataObj = templatesArray.get(0).getAsJsonObject().getAsJsonArray("data");
int dataSize = 0;
for (JsonElement jsonElement : dataObj){
if(jsonElement.getAsJsonObject().has("name")){
dataSize ++;
}
}
String value = dataObj.get(0).getAsJsonObject().get("value").getAsString();
String plantCode = null;
List<Detail> detailList = new ArrayList<>();
for (int i=0;i<dataSize;i++){
if (i==0){
plantCode = dataObj.get(i).getAsJsonObject().get("value").getAsString();
}else{
JsonArray detailsValue = dataObj.get(i).getAsJsonObject().getAsJsonArray("value");
Detail[] detail = gson.fromJson(detailsValue, Detail[].class);
for (Detail data : detail){
Detail detailInfo = new Detail();
detailInfo.setPlantMedicamentId(data.getPlantMedicamentId());
detailInfo.setPlantCode(data.getPlantCode());
detailInfo.setMedicamentName(data.getMedicamentName());
detailInfo.setMedicamentCode(data.getMedicamentCode());
detailInfo.setPresetsNumber(data.getPresetsNumber());
detailInfo.setDimension(data.getDimension());
detailInfo.setCreatUser(data.getCreatUser());
detailInfo.setCreatTime(data.getCreatTime());
detailInfo.setUpdateUser(data.getUpdateUser());
detailInfo.setUpdateTime(data.getUpdateTime());
detailList.add(detailInfo);
}
}
}
JsonArray detailsValue = dataObj.get(1).getAsJsonObject().getAsJsonArray("value");
log.info("测试数据如下:" + detailsValue);
}
Detail实体
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class Detail {
private int plantMedicamentId;
private String plantCode;
private String medicamentCode;
private String medicamentName;
private String presetsNumber;
private String dimension;
private String creatUser;
private String creatTime;
private String updateUser;
private String updateTime;
}
以上内容为举例,可以参考其中的某些步骤