java与ant design pro,request.js同时传多个对象,以及解析封装到具体的实体类
一,导入jsonjar包
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.56</version>
</dependency>
二,前台代码
1,首先保证你的params是以下格式,控制台输出如下:
我这里是一个对象+4个对象数组
2,实际请求的前台代码
export async function saveCostEstimateApportionForm(body:{list: any},options?: { [key: string]: any }) {
return request(`http://localhost:8006/costEa/saveCostApplyFor2`, {
method: "POST",
headers: {
'Content-Type': 'application/json',
},
data:body ,
// params: body,
...(options || {}),
paramsSerializer: (body) => stringify(body)
}).then(function(response) { console.log(response); }) .catch(function(error) { console.log(error); });
}
三,后台接口
通过mapj接收数据,并解析
@PostMapping("saveCostApplyFor2")
@ApiOperation(value = "保存费用预估/分摊单", notes = "")
public JsonResult saveCostApplyFo2(@RequestBody Map<String,Object> params) {
// 获取前台传的单个对象
Object obj = params.get("epaEstimateApportionMain");
ObjectMapper objectMapper = new ObjectMapper();
// 解析单个对象
EpaEstimateApportionMain epaEstimateApportionMain = objectMapper.convertValue(obj, EpaEstimateApportionMain.class);
// 获取前台传的对象数组
Object estimateApportionAttach1s = params.get("estimateApportionAttach1s");
// 先将对象转换为json格式的string
String jsonString = JSONArray.toJSONString(estimateApportionAttach1s);
// 转换为JSONArray
JSONArray jsonArray= JSONArray.parseArray(jsonString);
// 通过JSONArray的toJavaList方法转换为对象list
List<EpaEstimateApportionAttach1> estimateApportionAttach1List = jsonArray.toJavaList(EpaEstimateApportionAttach1.class);
//输出 ,验证是否接收到数据
for (EpaEstimateApportionAttach1 epaEstimateApportionAttach1 : estimateApportionAttach1List) {
System.out.println(epaEstimateApportionAttach1.toString());
}
return null;
}
如果有更好的方法,请大家留言指正,谢谢!