在 java spring boot 應用程式中嘗試使用 json 資料時,從 postmain 或 web 中的應用程式獲取錯誤的請求訊息。無法找到它的根本原因。
應用中使用的Json格式如下
{
"stateOfCharge": 30,
"timeSpendAtDest": 30,
"userId": 3745,
"distanceInMeters": 2478.91864342829,
"stationsList": [{
"csId": 50,
"csLat": 17.491125,
"csLng": 78.397686,
"energyLevel": "LEVEL1",
"maxChargeTimeInMins": 720,
"outPutRateInKw": 2,
"price": 0.8,
"distance": 126.31235091469274
}, {
"csId": 52,
"csLat": 17.491168,
"csLng": 78.398331,
"energyLevel": "LEVEL2",
"maxChargeTimeInMins": 480,
"outPutRateInKw": 19,
"price": 2.5,
"distance": 85.98535639001425
}, {
"csId": 50,
"csLat": 17.491125,
"csLng": 78.397686,
"energyLevel": "DCFAST",
"maxChargeTimeInMins": 30,
"outPutRateInKw": 350,
"price": 15,
"distance": 126.31235091469274
}]
}
像這樣撰寫的控制器并在 java 中得到 400 錯誤的請求回應
@PostMapping("/stations")
@ApiOperation(value = "Get charging stations around 400 radius from the charging location.")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Success"),
})
public void findChargingStations(
@ApiParam(value = "stateOfCharge") @NotNull @RequestParam Integer stateOfCharge,
@ApiParam(value = "timeSpendAtDest") @NotNull @RequestParam Integer timeSpendAtDest,
@ApiParam(value = "userId") @NotNull @RequestParam Integer userId,
@ApiParam(value = "distanceInMeters") @NotNull @RequestParam Integer distanceInMeters,
@RequestBody(value = "stationsList") @NotNull @RequestParam FindStations stationsList
) throws Exception {
this.findChargingStationsService.getFilteredStations(stateOfCharge, timeSpendAtDest, userId, distanceInMeters,stationsList);
return;
}
FindStations 是映射欄位的任何介面
public interface FindStations {
int getCsId();
double getCsLat();
double getCsLng();
float getPrice();
String getEnergyLevel();
int getMaxChargeTimeInMins();
int getOutPutRateInKw();
int getDistance();
}
可以幫助解決問題嗎
uj5u.com熱心網友回復:
您正在向后端發送一些復雜的資料。您可能希望在請求正文中發送它,而不是作為請求引數。
你可以使用@RequestBody它。
首先,讓我們創建一些 DTO 類來處理從前端發送的資料:
public class StationRequest {
private int stateOfCharge;
private int timeSpendAtDest;
private int userId;
private double distanceInMeters;
private List<Station> stationsList;
public int getStateOfCharge() {
return stateOfCharge;
}
public void setStateOfCharge(int stateOfCharge) {
this.stateOfCharge = stateOfCharge;
}
// Other getters and setters omitted for readability. You may want to consider project Lombok
}
public class Station {
private int csId;
private double csLat;
private double csLng;
private String energyLevel;
private int maxChargeTimeInMins;
private int outPutRateInKw;
private double price;
private double distance;
// Getters and setter omitted.
}
讓我們創建控制器:
@PostMapping("/stations")
public void findChargingStations(@RequestBody StationRequest stationRequest) {
// Do some business logic
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/460108.html
