I have a springboot rest service. The user passes in a json object that gets deserialized into this java pojo:
public final class Request {
private String id;
private double code;
private String name;
public String getId() {
return id;
}
public double getCode() {
return code;
}
public String getName() {
return name;
}
}
So the user needs to pass in the following json:
{
"id": “123457896”,
"code": "Foo",
"name": "test"
}
I want to make all of those fields required. Providing anything less or more will throw an exception. Is there a way to tell jackson to validate the input when it deserializes? I've tried @JsonProperty(required=true)
but this doesn't work; apparently from here and here it seems the JsonProperty
annotation is not respected.
I have this validator that I call in my controller:
@Component
public class RequestValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return false;
}
@Override
public void validate(Object target, Errors errors) {
String id = ((Request) target).getId();
if(id == null || id.isEmpty()) {
throw new InvalidRequestException("A valid id is missing. Please provide a non-empty or non-null id.");
}
}
}
But that just seems tedious and ugly to check every field. So given I'm using java 8, spring boot and latest version of jackson what is the best practice in terms of validating an incoming json input? Or am I already doing it in the most up to date manner?