Validate in Java that an incoming json matches the Class model

2

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?

    
asked by AndreFontaine 05.07.2016 в 20:20
source

1 answer

1

I recommend you use the instropection, with it you can dynamically validate your example:

Class[] classes = new Class[]{Module.class}
for(Class obj : classes){
            Object instance = obj.newInstance();
            for(Field field : obj.getFields()){
                //Aca compararias cada uno de los atributos de la clase con los elementos del json;

//
                }             }

    
answered by 13.07.2016 в 21:30