杰克逊条件验证字段

时间:2016-09-26 21:02:11

标签: java spring jackson json-deserialization

我正在尝试使用以下结构在Spring上设置Range Query结构:

public class QueryRange extends Query {

    @JsonProperty(required = true)
    @NotBlank
    @NotNull
    private String field;

    private Object gt;

    private Object gte;

    private Object lt;

    private Object lte;

    public String getField() {
         return field;
    }

    public QueryRange setField(String field) {
        this.field = field;
        return this;
    }

    public Object getGt() {
        return gt;
    }

    public QueryRange setGt(Object gt) {
        this.gt = gt;
        return this;
    }

    public Object getGte() {
        return gte;
    }

    public QueryRange setGte(Object gte) {
        this.gte = gte;
        return this;
    }

    public Object getLt() {
        return lt;
    }

    public QueryRange setLt(Object lt) {
        this.lt = lt;
        return this;
    }

    public Object getLte() {
        return lte;
    }

    public QueryRange setLte(Object lte) {
        this.lte = lte;
        return this;
    }

    @AssertTrue(message = "Invalid range. A value for 'gt' or 'lt' should be set.")
    private boolean isRangeSpecified() {
        return this.gt != null || this.lt != null;
    }

    @AssertTrue(message = "Invalid range data type. 'gt' and 'lt' must be of the same type.")
    private boolean isRangeDataTypeValid() {
        if (this.gt != null && this.lt != null) {
            return this.gt.getClass().equals(this.lt.getClass());
        }

        return true;
    }
}

问题是 gt,gte,lt或lte 中的至少一个值不应为null。我该如何验证?

我在上面的代码示例中尝试过Bean验证,但它没有用。有什么建议吗?

1 个答案:

答案 0 :(得分:0)

您应该使用Class-level约束。

  

最后但并非最不重要的是,约束也可以放在类级别上。在这种情况下,不是单个属性是验证的主题,而是完整的对象。如果验证取决于对象的多个属性之间的相关性,则类级约束很有用。

@ValidQueryRange
public class QueryRange extends Query {
    // your class here...
    private Object gt;

    private Object gte;

    private Object lt;

    private Object lte;
}
@Target({ TYPE, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = { ValidQueryRangeValidator.class })
@Documented
public @interface ValidQueryRange {

    String message() default "{error}";

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

    Class<? extends Payload>[] payload() default { };
}
public class ValidQueryRangeValidator implements ConstraintValidator<ValidQueryRange, QueryRange> {

    @Override
    public void initialize(ValidQueryRange constraintAnnotation) {
    }

    @Override
    public boolean isValid(QueryRange queryRange, ConstraintValidatorContext context) {
        if ( queryRange == null ) {
            return true;
        }
        // put your logic here
        if ( queryRange.getGt() == null || queryRange.getLt() == null) {
            return false;
        }

        return true;
    }
}