You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot中如何获取不属于任何类的请求参数并解决反序列化报错

问题解决思路

错误根因

你在Controller层将@RequestBody直接注解在double amount参数上,要求请求体直接传入纯数字,但实际调用方传入的是标准JSON对象(结构类似{"amount": 100.5, "accountType": "Permanent", "accountNumber": 12345}),Jackson反序列化时识别到JSON起始符{,无法直接转换为double类型,因此抛出对应报错。

修正步骤

1. 新增请求参数封装DTO

专门定义类接收接口传入的所有参数,避免零散参数绑定错误:

// DepositRequest.java
import java.math.BigDecimal;

public class DepositRequest {
    private BigDecimal amount;
    private String accountType;
    private int accountNumber;

    //  getter、setter方法
    public BigDecimal getAmount() {return amount;}
    public void setAmount(BigDecimal amount) {this.amount = amount;}
    public String getAccountType() {return accountType;}
    public void setAccountType(String accountType) {this.accountType = accountType;}
    public int getAccountNumber() {return accountNumber;}
    public void setAccountNumber(int accountNumber) {this.accountNumber = accountNumber;}
}

注:金额字段直接用BigDecimal类型,避免double转BigDecimal出现的精度丢失问题

2. 修正Controller层代码

统一用DTO接收请求体,删除无效的零散参数:

@PostMapping("/deposit")
public ResponseEntity<Object> depositPost(@RequestBody DepositRequest request){
    // 可自行添加参数非空校验逻辑
    accountService.deposit(request.getAccountType(), request.getAccountNumber(), request.getAmount());
    return ResponseEntity.ok("Record has been entered");
}

3. 对齐Service层方法签名,补充异常判断

修正AccountService接口:

public interface AccountService {
    // 统一参数顺序,金额改为BigDecimal避免精度问题
    void deposit(String accountType, int accountNumber, BigDecimal amount);
}

修正AccountServiceImpl实现类:

@Override
public void deposit(String accountType, int accountNumber, BigDecimal amount) {
    if (accountType.equalsIgnoreCase("Permanent")) {
        Account account = accountDao.findByAccountNumber(accountNumber);
        // 补充账户不存在的判断,避免空指针
        if (account == null) {
            throw new RuntimeException("对应账户不存在");
        }
        account.setAccountBalance(account.getAccountBalance().add(amount));
        accountDao.save(account);
    }
    // 可补充其他accountType的处理逻辑
}

注:你之前代码中同时出现accountRepository和accountDao变量,你的持久层接口命名是AccountDao,请统一注入的变量名,避免编译错误

内容的提问来源于stack exchange,提问作者Seeschon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 07:39:01