POST 使用 Java/Spring-boot 请求端点

POST request endpoint using Java/Spring-boot

我正在尝试创建一个 post 请求端点以将一些表单值发送到我的数据库。当我用 postman 测试请求时,我收到 400 错误请求错误,并且在我的控制台中显示此消息

JSON 解析错误:无法从数组值(标记 JsonToken.START_ARRAY)中反序列化 abcd.Model.Quote 类型的值;

这是我的控制器:

    @ResponseStatus(HttpStatus.CREATED)
    @PostMapping("/createQuote")
    public boolean newQuote(@RequestBody Quote newQuote) {
    return quoteDB.saveQuote(newQuote);
};

我的模特:

public class Quote {
public int id;
public String type_building;
public int numElevator;
public String typeService;
public double total;
public double totalElevatorPrice;

public Quote(
        int _id,
        String _type_building,
        int _numElevator,
        String _typeService,
        double _total,
        double _totalElevatorPrice
){
    this.id = _id;
    this.type_building = _type_building;
    this.numElevator = _numElevator;
    this.typeService = _typeService;
    this.total = _total;
    this.totalElevatorPrice = _totalElevatorPrice;

}
public String getType_building() { return type_building; }
public void setType_building(String type_building) { this.type_building = type_building; }

public int getNumElevator() { return numElevator; }
public void setNumElevator(int numElevator) { this.numElevator = numElevator; }

public String getTypeService() { return typeService; }
public void setTypeService(String typeService) { this.typeService = typeService; }

public double getTotal() { return total; }
public void setTotal(int total) { this.total = total; }

public double getTotalElevatorPrice() { return totalElevatorPrice; }
public void setTotalElevatorPrice(int totalElevatorPrice) { this.totalElevatorPrice = totalElevatorPrice; }

}

这是我尝试 post 到数据库的函数 saveQuote:

    public boolean saveQuote(Quote newQuote){
    PreparedStatement getData;
    try {
        Connection c;
        c  = this.db.connectDB();
        getData = c.prepareStatement("INSERT INTO Quote VALUES (" +"'" +newQuote.getType_building() + "'" +"," + "'" +newQuote.getNumElevator() + "'" + "," + newQuote.getTypeService() + "," + newQuote.getTotal() + "," + newQuote.getTotalElevatorPrice() + ")");
        getData.executeUpdate();
        return true;
    }
    catch (SQLException e) {
        e.printStackTrace();
    }
    return false;
}

感谢您的帮助。

更新:这是我在 postman:

中发送的 POST 请求
[
{
    "id": 2,
    "type_building": "commercial",
    "numElevator": 10,
    "typeService": "standard",
    "total": 100000.0,
    "totalElevatorPrice": 1.0E7
}
]
@PostMapping("/createQuote")
public boolean newQuote(@RequestBody Quote newQuote) {

您的控制器希望输入一个表示您在代码中定义的报价对象的对象 { ... }

Cannot deserialize value of type abcd.Model.Quote from Array value (token JsonToken.START_ARRAY);

但是您将发送对象数组的消息作为输入提供 [ {...}, {...}]

您的请求必须没有 [ ],因为如果您的控制器需要一个对象数组,就应该使用这些。

应该是

{
    "id": 2,
    "type_building": "commercial",
    "numElevator": 10,
    "typeService": "standard",
    "total": 100000.0,
    "totalElevatorPrice": 1.0E7
}