如何配置 Spring 以使用 @RequestBody 注释将 JSON 反序列化为 BigDecimal



当我发布到端点"/test"时,我的大十进制为空。

我正在发布的有效载荷:

{
  "decimalOne": "230.0",
  "decimalTwo": "215.0"
}

我的对象类:

public class MyObject {
    private BigDecimal decimalOne;
    private BigDecimal decimalTwo;
    public MyObject() {
    }
    public MyObject(BigDecimal decimalOne, BigDecimal decimalTwo) {
        this.decimalOne = decimalOne;
        this.decimalTwo = decimalTwo;
    }
    BigDecimal getDecimalOne() {
        return decimalOne;
    }
    BigDecimal getDecimalTwo() {
        return decimalTwo;
    }
}

控制器:

@RestController
@RequestMapping("/test")
public class MyObjectController {
    private DecimalService decimalService;
    @Inject
    MyObjectController(DecimalService decimalService){
        this.decimalService = decimalService;
    }
    @PostMapping
    public Integer getNumberBack(@RequestBody MyObject myObjectPayload){
       return decimalService.getNumber(myObjectPayload);
    }
}

如何让 Spring 将 JSON 反序列化为 BigDecimal。如果我遗漏了任何信息,也请告诉我。谢谢!

您需要将 setter 添加到 MyObject,因为在使用 MyObject(( 反序列化程序创建对象后,没有合法的方式来设置字段。

最新更新