我想检查输入参数是否是有效的json。它可以是任何东西:map,string,number等是否有一些准备使用hibernate验证器呢?
为了更清楚,我正在寻找类似于@Email
的类似内容。是否有@Json
之类的注释?
答案 0 :(得分:1)
没有Json验证器,但您可以连接自定义验证器
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;
}
}