Search code examples
springvalidationspring-mvcnested-class

Spring MVC nested object validation


I have the following code in my controller

@RequestMapping(value = "employee/update", method = RequestMethod.POST, headers = "Accept=application/json")
    public UpdateEmployeeResponse updateEmployee(@RequestBody @Valid @ModelAttribute("updateEmployeeRequest") UpdateEmployeeRequest updateEmployeeRequest, BindingResult result) {

My Request object is as follows

public class UpdateEmployeeRequest {
@Valid
@NotNull
private Employee employee;
.
.

public class Employee {
@NotNull
protected String id;
@NotNull
protected String name;
.
.

When I send JSON request like (id is missing)

{employee:{name:"cc",phone:"9876543210",dept:"dpt"}}

My Request is not getting validated by spring(it doesn't show any error even if a field is missing). I have gone through the following threads but no luck.

Can anyone help?


Solution

  • To ignore any unknown properties in JSON input without exception try using @JsonIgnoreProperties(ignoreUnknown=true).

    Try this out

    Employee.java

    @JsonIgnoreProperties(ignoreUnknown = true)
    public class Employee
    {
     @NotNull
     protected String id;
     @NotNull
     protected String name;
     .
     .
    

    UpdateEmployeeRequest.java

    @JsonIgnoreProperties(ignoreUnknown = true)
    public class UpdateEmployeeRequest {
     @Valid
     @NotNull
     private Employee employee;
     .
     .