@NotEmpty 和@notNull 在反序列化期间不起作用

@NotEmpty and @notNull not working during deserialization

我有一段代码将 json 字符串反序列化为模型对象,但是我提供了 @NotNull 和 @NotEmpty 验证但它不起作用,下面是代码:-

   private Student getDecryptedRequestData(String studentRequest) throws JsonParseException, JsonMappingException, IOException {
    
    return  new ObjectMapper().readValue(studentRequest,Student.class);
}

Student.java

   import javax.validation.constraints.NotEmpty;
   import javax.validation.constraints.NotNull;

   import com.fasterxml.jackson.annotation.JsonProperty;

   public class Student{


    @NotEmpty
    private String studentName;

    @NotNull
    private Long roll;

   public String getStudentName() {
    return studentName;
   }

public void setStudentName(String studentName) {
    this.studentName= studentName;
}


public Long getRoll() {
    return roll;
}

public void setRoll(Long roll) {
    this.duration = roll;
}

}

在你之前return你可以使用的学生

Validation.buildDefaultValidatorFactory().getValidator().validate(Student);

或使用组件

 @Component
@Slf4j
public class ValidatorUtils {
    private final ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
    private final Validator validator = validatorFactory.getValidator();

    public <T> void checkValid(T object, Class<?>... groups) {
        Set<ConstraintViolation<T>> set = validator.validate(object, groups);
        if (CollectionUtils.isNotEmpty(set)) {
            throw new ConstraintViolationException(set);
        }
    }

}

在下面的代码中使用它并且在 POJO 的构造函数中添加了@JsonCreator

    ObjectMapper mapper = new ObjectMapper();
 mapper.configure(DeserializationFeature.FAIL_ON_NULL_CREATOR_PROPERTIES, true);