I need to validate a json that comes from the request body, some fields are required but if the json does not have them, they are returned as null:
@Document(collection = "menus")
public class Module {
/** The module name as unique identifier. */
@Indexed(unique = true)
private String name;
/** The internationalization key. */
private String i18n;
/** The Angular state. */
private String state;
...
}
If the json arrives with a structure without the name field, for example:
{
"i18n": "INVOICES",
"state": "/invoices"
}
The Module is valid and persisted as:
{
"name": null,
"i18n": "INVOICES",
"state": "/invoices"
}
To validate this field in the json that arrives, create a Validator like this:
public class MenuValidator implements Validator {
/** The menu service. */
private MenuService service;
public MenuValidator(MenuService service) {
this.service = service;
}
@Override
public boolean supports(Class<?> objectClass) {
return objectClass.equals(Module.class);
}
@Override
public void validate(Object object, Errors errors) {
try {
String name = ((Module) object).getName());
if(name==null){
errors.rejectValue("name", "name.null","The module name is null");
}
...
}
However, this is very cumbersome, especially if the model becomes more complex because it would be necessary to validate many fields. Is there an option to make these validations more automatically?