简体   繁体   中英

Java validate incoming json matches with the model Class

I need to validate an incoming json from a request body, some fields are required but if the json doesn't have it, they are just retrieved 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 incoming json have this structure, without name:

{
    "i18n": "INVOICES",
    "state": "/invoices"
}

the Module is valid and persisted as:

{
    "name": null,
    "i18n": "INVOICES",
    "state": "/invoices"
}

To validate this incoming json I 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");
           }
    ...
}

But this is so tricky, when I have a complex structure and I need to validate all fields. Is there any options to validate my structure without validate field by field?

No i don't think there is any other alternative for such validations. You need to manually check for each property.

Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM