4

I want to validate List of Maps and keys in Maps in my Json request. But how to add custom annotation for generic type Map in List ? Please look at below code.

When I try like this, CheckKeysMapValidator class does not get executed.

-------Part of JSON request-------

  "attributes": [{
                        "name": "Chandra",
                        "address": "India"
                    },
                    {       "name": "Sam",
                        "address": "US"
                    },
                    {
                        "name": "David",
                        "address": "England"
                    }
                ], 

------------Model Class----------

 Class RequestTO{
    @NotEmpty(message = "'attributes' is required.")   
       @Valid
       private List< @CheckKeysForMap(
             message = "'attributes' must contain two properties as 'name' and 'address'.",
             value = { "name", "address" }) Map<String, String>> attributes;


              public List<Map<String, String>> getAttributes() {
          return attributes;
       }

       public void setAttributes(List<Map<String, String>> attributes) {
          this.attributes = attributes;
       }

    }

-------Custom annotation -----------

import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.LOCAL_VARIABLE;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.ElementType.TYPE_PARAMETER;
import static java.lang.annotation.ElementType.TYPE_USE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;
import javax.validation.constraints.NotNull;

/**
 * Marks the Map property to check if Map contains defined keys or not.
 *
 */

@Target({ FIELD, PARAMETER, TYPE_USE, TYPE, TYPE_PARAMETER, LOCAL_VARIABLE, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Documented
@NotNull
@Constraint(validatedBy = { CheckKeysMapValidator.class })
public @interface CheckKeysForMap {
    String message() ;
    Class<?>[] groups() default { };
    Class<? extends Payload>[] payload() default { };
    String[] value() ;  

}

---------------------Validator Class-----------------

 import java.util.Map;
    import java.util.TreeMap;

    import javax.validation.ConstraintValidator;
    import javax.validation.ConstraintValidatorContext;

    public class CheckKeysMapValidator implements ConstraintValidator<CheckKeysForMap, Map<String, ?>> {

       String[] requiredKeys;
       String emptyString = "";

       @Override
       public void initialize(CheckKeysForMap constraintAnnotation) {
          requiredKeys = constraintAnnotation.value();

       }

       @Override
       public boolean isValid(Map<String, ?> map, ConstraintValidatorContext context) {
          if (map.isEmpty()) {
             return false;
          }

          for (String requiredKey : requiredKeys) {
             requiredKey = requiredKey.toLowerCase();
             Map<String, Object> lowerCaseMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
             lowerCaseMap.putAll(map);
             if (!lowerCaseMap.containsKey(requiredKey) || lowerCaseMap.containsValue(emptyString)) {
                return false;
             }

          }
          return true;
       }

    }
1
  • it'll be also good to see how you are actually doing the validation. Can you add that code snippet as well ?
    – mark_o
    Jul 15, 2019 at 8:38

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.