【问题标题】:How to configure Spring to deserialize JSON into a BigDecimal using a @RequestBody annotation如何配置 Spring 以使用 @RequestBody 注释将 JSON 反序列化为 BigDecimal
【发布时间】:2019-10-19 03:08:00
【问题描述】:

当我发布到端点“/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
  • 我会尝试,但我很确定 Spring 只需要一个空的构造函数和 getter。添加 setter 似乎会消除封装的目的。
  • 那行得通。由于封装冲突,这对我来说没有多大意义,但谢谢。你能回答这个问题,我会接受吗?谢谢!
  • 我认为您也可以使用 @JsonProperty 注释字段(如果您不想使用 setter)。
  • 太棒了,谢谢!必须在要反序列化的每个变量上添加 @JsonProperty 似乎有点乏味。

标签: java json spring spring-boot deserialization


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-14
    • 2019-09-05
    • 1970-01-01
    • 1970-01-01
    • 2012-03-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多