我想检查我的输入参数是否为有效的json。它可以是任何东西:映射,字符串,数字等。为此是否准备好使用休眠验证器?

为了更加清楚,我正在寻找类似于@Email的东西。是否有类似@Json的注释?

最佳答案

没有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;
 }

}

10-04 21:11