java的Validator如何检测集合中的对象的属性
解决方法:
在对象属性上加上注解@Valid
例如下面就是检测SurveyDesignData对象中的Question对象的title字数不能超过500
public class SurveyDesignData {
@Valid
List<Question> questions;//问卷调查项信息
}
public class Question {
@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));
}