我偶然发现了一个有趣的案例,但不确定如何解决。它可能与JSON Post request for boolean field sends false by default有关,但该文章的建议无济于事。
让我说我上了这个课:
public class ReqBody {
@NotNull
@Pattern(regexp = "^[0-9]{10}$")
private String phone;
//other fields
@NotNull
@JsonProperty(value = "create_anonymous_account")
private Boolean createAnonymousAccount = null;
//constructors, getters and setters
public Boolean getCreateAnonymousAccount() {
return createAnonymousAccount;
}
public void setCreateAnonymousAccount(Boolean createAnonymousAccount) {
this.createAnonymousAccount = createAnonymousAccount;
}
}
我也有端点:
@PostMapping(value = "/test", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<MyOutput> test(
@ApiParam(value = "information", required = true) @RequestBody ReqBody input
) {
//do something
}
问题是我将请求正文发送为:
{
"phone": "0000000006",
"create_anonymous_account": null
}
或就像
{
"phone": "0000000006"
}
将createAnonymousAccount设置为false。
我已检查并正确识别"create_anonymous_account": true
有什么方法可以在布尔字段中“强制”空值?
我真的需要知道它是否已发送,并且没有默认值。
答案 0 :(得分:1)
您可以使用Jackson注释忽略空字段。如果呼叫者未发送createAnonymousAccount,则它将为null。
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ReqBody {
@NotNull
@Pattern(regexp = "^[0-9]{10}$")
private String phone;
//other fields
@JsonProperty(value = "create_anonymous_account")
private Boolean createAnonymousAccount ;
}