Need to Reject POST/PUT request if any unknown field is present in RequestBody

Viewed 1671

@Valid check is working for respective fields. Is there any way to reject requests if any unknown fields are present in JSON requestbody of POST/PUT requests.Below is my sample DTO class and controller. For below sample request body (for example), the request should be rejected/throw exception. Any help or suggestion would be appreciated.

{
"accountid" : "P12345",
"name" : "Cardiology",
"domain" : "Apollo"
}

public class Account {

    @NotEmpty(message = "accountid is required")
    private String accountid;

    @NotEmpty(message = "name is required")
    private String name;

   //getters & setters

}

**********************************************************************************************

public class BeanController {

    @PostMapping(path = "/accounts")
    public ResponseEntity<?> getAllAccounts(@RequestBody @Valid Account account) {

        System.out.println("::: Account is " + account + " :::");

        return ResponseEntity.ok().body("SUCCESS");

    }
}
1 Answers

You can do it by using @JsonIgnoreProperties.

@JsonIgnoreProperties(ignoreUnknown = true)
public class Account {

    @NotEmpty(message = "accountid is required")
    private String accountid;

    @NotEmpty(message = "name is required")
    private String name;

   //getters & setters

}

Add below properties in application.yml to working in spring-boot latest version.

spring:
  jackson:
    deserialization:
      fail-on-unknown-properties: true
Related