【问题标题】:Sending java.lang.Boolean over JSON (Spring Boot)通过 JSON (Spring Boot) 发送 java.lang.Boolean
【发布时间】:2018-12-09 12:42:39
【问题描述】:

我有一个带有布尔(不是原始布尔)属性的 bean。这是因为该属性与此类的每个实例都不相关,因此应该是nullable

Bean 在创建 REST 服务上作为 JSON 发送。控制器接收到null,而不是实际值。

我的控制器:

@RestController
@RequestMapping("/myBean")
public class MyBeanController {

    @Autowired
    private MyBeanService myBeanService;

    @PostMapping("/create" )
    public ResponseEntity createTransaction(@RequestBody MyBeanDTO myBean) {
        MyBeanDTO result = myBeanService.create(myBean);
        return new ResponseEntity(result, HttpStatus.OK);
    }
}

我的豆子:

public class MyBean  {

    . . .
    private Boolean active;
    . . .

    public Boolean getActive() { //Instead of isActive, as it's Boolean and not boolean
        return active;
    }

    public void setActive(Boolean active) {
        this.active = active;
    }
}

我发送的所有 JSON 都没有正确解析“活动”属性,并且始终以 null 的形式出现。我试过 true,“true”,{“value”:true}。我错过了什么?

【问题讨论】:

    标签: java json spring spring-boot boolean


    【解决方案1】:

    @JsonProperty 添加到字段:

    @JsonProperty("active")
    private Boolean active
    

    可用于将非静态方法定义为逻辑属性(取决于其签名)或要使用的非静态对象字段(序列化、反序列化)的“setter”或“getter”的标记注释作为一个逻辑属性。

    如果它不起作用,请在 MyBeanDTO 方法中删除 @RequestBody 之前的 createTransaction 方法

    【讨论】:

    • @JsonProperty 通过在 JSON 中使用 "active" : true 解决了我的问题。非常感谢!
    • @MiguelBHM 如果有帮助,您可以接受我的回答,请参阅stackoverflow.com/help/someone-answers
    猜你喜欢
    • 2020-12-22
    • 2017-02-09
    • 2020-11-15
    • 2017-10-15
    • 1970-01-01
    • 2021-07-23
    • 2017-11-08
    • 2022-12-02
    • 2018-09-11
    相关资源
    最近更新 更多