Throw error when properties marked with @JsonIgnore are passed

Viewed 259

I have a requirement to mark certain properties in my REST beans as ignored using @JsonIgnore. (I am using Spring Boot). This helps in avoiding these properties in my Swagger REST documentation.

I also would like to ensure that if the client passes these properties, an error is sent back. I tried setting spring.jackson.deserialization.fail-on-unknown-properties=true, but that works only for properties that are truly unknown. The properties marked with @JsonIgnore passes through this check.

Is there any way to achieve this?

1 Answers

I think I found a solution -

If I add @JsonProperty(access = Access.READ_ONLY) to the field that is marked as @JsonIgnore, I get back a validation error. (I have also marked the property with @Null annotation. Here is the complete solution:

@JsonInclude(JsonInclude.Include.NON_NULL)
public class Employee {
  @Null(message = "Id must not be passed in request")
  private String id;
  
  private String name;

  //getters and setters
}

@JsonInclude(JsonInclude.Include.NON_NULL)
public class EmployeeRequest extends Employee {
  @Override
  @JsonIgnore
  @JsonProperty(access = Access.READ_ONLY)
  public void setId(String id) {
    super.setId(id);
  }
}

PS: By adding @JsonProperty(access = Access.READ_ONLY), the property started showing up in Swagger model I had to add @ApiModelProperty(hidden = true) to hide it again. The create method takes EmployeeRequest as input (deserialization), and the get method returns Employee as response (serialization). If I pass id in create request, with the above solution, it gives me back a ConstraintViolation.

PS PS: Bummer. None of these solutions worked end-to-end. I ended up creating separate request and response beans - with no hierarchical relationship between them.

Related