7

@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");

    }
}
Balaji211
  • 257
  • 1
  • 5
  • 18
  • 1
    You got your answer already. However, I would advice strongly against doing this unless you are sure of it. Reason is, with this, now you have a bit more tight coupling between your producer and consumer. Let's say you want to enhance your API and add a new mandatory field on your producer side. Now you have to manage the release of your producer and consumer simultaneously. you could ask all your consumers to upgrade first and upgrade your producer only after all your consumers upgraded. You are losing that flexibility with this deserialization property. – so-random-dude Apr 08 '20 at 16:06
  • Thanks for the suggestion. But we need it like that only as part of our security norms. – Balaji211 Apr 09 '20 at 12:51

1 Answers1

6

You can do it by using @JsonIgnoreProperties.

@JsonIgnoreProperties(ignoreUnknown = false)
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
GolamMazid Sajib
  • 8,698
  • 6
  • 21
  • 39