3

I'd like to check if my input parameter is a valid json. it can be anything: map, string, number etc. is there some ready to use hibernate validator for this?

to make it more clear, i'm looking for something similar to, for example, @Email. Is there any annotation like @Json?

piotrek
  • 13,982
  • 13
  • 79
  • 165
  • 1
    How is your question different from other questions on SO as [this](https://stackoverflow.com/questions/10174898/how-to-check-whether-a-given-string-is-valid-json-in-java), [this](https://stackoverflow.com/questions/32038543/how-to-validate-a-json-object-in-java), [this](https://stackoverflow.com/questions/10226897/how-to-validate-json-with-jackson-json) and many others? – jannis Nov 23 '16 at 14:07
  • 3
    @jannis these questions have nothing to do with `spring-mvc` and `hibernate-validation`. – alex Nov 23 '16 at 14:18
  • I misread the question. My bad. – jannis Nov 23 '16 at 20:47

1 Answers1

1

No Json validator as such, but you can wire a custom validator

public class Customer {

    @Size(min=2, max=30) 
    private String name;

    @NotEmpty @Email
    private String email;

    @JsonValid
    private String  json;

}

@Documented
@Constraint(validatedBy = JsonValidator.class)
@Target( { ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface JsonValid {


    String message() default "{JsonValid}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

}

public class JsonValidator implements ConstraintValidator < JsonValid, String > {

 @Override
 public void initialize(JsonValid value) {}

 @Override
 public boolean isValid(String json, ConstraintValidatorContext ctx) {

  ObjectMapper mapper = new ObjectMapper();
  ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
  Validator validator = factory.getValidator();

  //validate with your request object
  SimpleFooRequest request = mapper.readValue(
   json, SimpleFooRequest.class);
  Set < ConstraintViolation < SimpleFooRequest >> violations = validator.validate(request);

  return  violations.size() > 0;
 }

}    
kuhajeyan
  • 10,727
  • 10
  • 46
  • 71
  • Shouldn't it be `return violations.size() == 0;`? – jannis Nov 23 '16 at 20:50
  • And wouldn't `mapper.readValue(json, SimpleFooRequest.class);` throw an exception on invalid JSON? I guess it would be enough to try-catch this line and use it as indication of JSON validity. – jannis Nov 23 '16 at 22:11