4

I've stumbled upon interesting case and I'm not sure how to resolve it. It's probably related to JSON Post request for boolean field sends false by default but advices from that article didn't help.

Let's say I have this class:

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;
    }
}

I also have endpoint:

@PostMapping(value = "/test", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<MyOutput> test(
            @ApiParam(value = "information", required = true) @RequestBody ReqBody input
    ) {
//do something
}

problem is when I send my request body as:

{
"phone": "0000000006",
 "create_anonymous_account": null
}

or just like

{
"phone": "0000000006"
}

it sets createAnonymousAccount to false.

I have checked, and it correctly recognises "create_anonymous_account": true

Is there any way to "force" null value in boolean field?

I really need to know if it was sent or no, and not to have default value.

Sheyko Dmitriy
  • 383
  • 1
  • 3
  • 15
  • 1
    You annotated the field with `@NotNull` -> seems like a copy-paste-error / a typo? – Lino Dec 23 '19 at 16:08
  • It's strange to annotate the field with `@NotNull` and to initialize it with `createAnonymousAccount = null` – jhamon Dec 23 '19 at 16:15
  • I wanted it not to be null (so it won't pass validation if not set), but make it null by defalut (so that ```{"phone": "0000000006"}``` won't pass validation) – Sheyko Dmitriy Dec 24 '19 at 07:28
  • Whoever still looks how to pass optional parameters via `@RequestBody` (not just whole body optional), make sure your boolean field is declared `private Boolean` and not `private boolean` then it may have `null`/`true`/`false` values. – simno Jun 10 '21 at 15:16

1 Answers1

4

You can use Jackson annotation to ignore the null fields. If the Caller doesn't send createAnonymousAccount then it will be 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 ;
}
dassum
  • 4,727
  • 2
  • 25
  • 38