java的Validator如何检测对象属性中的属性
解决方法:
在对象属性上加上注解@Valid
例如下面就是检测SurveyDesignData对象中的survey对象的title字数不能超过500
public class SurveyDesignData {
@Valid
Survey survey;
}
public class Survey {
@Size(max = 500)
private String title;
}
SurveyDesignData surveyDesignData = JSON.parseObject(content, SurveyDesignData.class);
Set<ConstraintViolation<SurveyDesignData>> set = validator.validate(surveyDesignData);
if (set.size() > 0) {
List<String> errorMessage = new ArrayList<>();
set.forEach(it ->
errorMessage.add(it.getPropertyPath() + " : " + it.getMessage())
);
throw new Exception(JSON.toJSONString(errorMessage));
}