I receive a json encoded string and then I decode it into a pojo, like this:
String json = ...
final ObjectMapper mapper = new ObjectMapper();
MyPojo obj = mapper.readValue(json, MyPojo.class);
I want to be able to validate this input, but I'm not sure what's the "right way" of doing it.
Let's say MyPojo is defined like this:
@JsonIgnoreProperties(ignoreUnknown=true)
class MyPojo {
public static enum Type {
One,
Two,
Three;
@JsonValue
public String value() {
return this.name().toLowerCase();
}
}
private String id;
private Type type;
private String name;
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
public Type getType() {
return this.type;
}
public void setType(Type type) {
this.type = type;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
There are three things I want to validate:
If the validation fails I want to return a meaningful and readable message.
For the first and third issues I can simply check all the members of the object and see if any are null, and if not test them against the criteria, but this approach can get long and complicated when there are many fields.
As for the 2nd issue, if the value in the input does not match one of the enumeration values then a JsonMappingException
is thrown, and so I managed to do this:
try {
MyPojo obj = mapper.readValue(json, MyPojo.class);
}
catch (JsonMappingException e) {
return "invalid value for property: " + e.getPath().get(0).getFieldName();
}
But how do I get the value in the input so that I can return: invalid value: VALUE for property: PROPERTY
?
Thanks.
I would recommend using an implementation of JSR-303 Bean Validation. This specification defines a set of annotations and XML config files for specifying constraints that you wish to validation on your domain obects. The reference implementation is available here:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With