繁体   English   中英

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

[英]How to configure Spring to deserialize JSON into a BigDecimal using a @RequestBody annotation

当我发布到端点“ / test”时,我的BigDecimals为空。

我发布的有效载荷:

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

MyObject类:

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。 另外,如果我遗漏了任何信息,请告诉我。 谢谢!

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM