後臺如何接受前端傳過來的物件陣列最簡單的解決方法
下面給個錯誤的列子
/**
* 採購退貨資訊新增
*/
@PostMapping("/purchasereturngoods/insert")
@ApiOperation("採購退貨資訊批量新增")
public R insertPurchaseReturnGoods(
@ApiParam("員工Id:必須")@RequestParam (value="employeeId",required=true) int employeeId,
@ApiParam("採購單Id:必須")@RequestParam (value="purchaseOrderId",required=true) int purchaseOrderId,
@RequestBody List<PurchaseReturnGoods> purchasereturngoodsList){
//獲取使用者ID
Long userId = getUserId();
return busBaseService.insertReturnGoods(userId,purchaseOrderId,purchasereturngoodsList);
}
後臺這樣接收前端傳過來的陣列接收不到的,因為前臺預設傳的是一個物件,但是你用List去接受它就會報Json解析錯誤。
為了解決這個問題,我們可以把List<PurchaseReturnGoods>封裝到一個物件裡在接收前端穿的陣列物件:
public class PurchasereturngoodsList implements Serializable {
private static final long serialVersionUID = 1L;
private List<PurchaseReturnGoods> prgList;
public List<PurchaseReturnGoods> getPrgList() {
return prgList;
}
public void setPrgList(List<PurchaseReturnGoods> prgList) {
this.prgList = prgList;
}
}
PurchasereturngoodsList 是新封裝的物件,對應的後臺接收方式就要改變
/**
* 採購退貨資訊新增
*/
@PostMapping("/purchasereturngoods/insert")
@ApiOperation("採購退貨資訊批量新增")
public R insertPurchaseReturnGoods(
@ApiParam("員工Id:必須")@RequestParam (value="employeeId",required=true) int employeeId,
@ApiParam("採購單Id:必須")@RequestParam (value="purchaseOrderId",required=true) int purchaseOrderId,
@ApiParam("採購單Id:prgList")@RequestBody PurchasereturngoodsList purchasereturngoodsList){
//獲取使用者ID
Long userId = getUserId();
return busBaseService.insertReturnGoods(userId,purchaseOrderId,purchasereturngoodsList.getPrgList());
}
可以看到,接收從List<PurchaseReturnGoods>一個數組變成了PurchasereturngoodsList一個物件,purchasereturngoodsList.getPrgList()就能獲取到前端傳到後臺的物件陣列了。
注意:前端往後臺傳物件的時候引數名要和你封裝的物件裡面的屬性名一致,在我這個模板裡前端的引數名就是prgList,而不是purchasereturngoodsList。