首页 文章

通过JSON发送java.lang.Boolean(Spring Boot)

提问于
浏览
2

我有一个带有布尔(非原始布尔)属性的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);
    }
}

我的 beans 子:

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都没有正确解析属性"active",并始终为 null . 我试过了,"true",{"value":true} . 我错过了什么?

1 回答

  • 1

    @JsonProperty添加到字段:

    @JsonProperty("active")
    private Boolean active
    

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

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

相关问题