繁体   English   中英

Spring 控制器中的 JSR-303 验证并获取 @JsonProperty 名称

[英]JSR-303 validation in Spring controller and getting @JsonProperty name

我在我的 Spring 应用程序中使用JSR-303进行验证,它可以根据需要工作。

这是一个例子:

@Column(nullable = false, name = "name")
    @JsonProperty("customer_name")
    @NotEmpty
    @Size(min = 3, max = 32)
    private String name;

并且 REST API 客户端使用customer_name作为输入字段的名称,该名称发送到 API 芽验证字段错误org.springframework.validation.FieldError返回name作为字段的名称。

有什么方法可以获取在@JsonProperty中指定的JSON-ish风格的名称吗? 还是我必须实现自己的映射器将类字段名称映射到其 JSON 替代项?

Edit1:将类字段重命名为与 JSON 名称相对应的名称是不可替代的(出于多种原因)。

这现在可以通过使用PropertyNodeNameProvider来完成。

目前没有办法实现这一点。 我们在参考实现中有一个问题: HV-823

这将解决 Hibernate Validator 方面的问题(即从Path.Node#getName()返回您期望的名称),它需要更多检查 Spring 是否真的从那里获取名称。

也许您有兴趣帮助实现这个?

对于MethodArgumentNotValidExceptionBindException ,我编写了一个尝试通过反射从 Spring ViolationFieldError访问私有ConstraintViolation的方法。

  /**
   * Try to get the @JsonProperty annotation value from the field. If not present then the
   * fieldError.getField() is returned.
   * @param fieldError {@link FieldError}
   * @return fieldName
   */
  private String getJsonFieldName(final FieldError fieldError) {
    try {
      final Field violation = fieldError.getClass().getDeclaredField("violation");
      violation.setAccessible(true);
      var constraintViolation = (ConstraintViolation) violation.get(fieldError);
      final Field declaredField = constraintViolation.getRootBeanClass()
          .getDeclaredField(fieldError.getField());
      final JsonProperty annotation = declaredField.getAnnotation(JsonProperty.class);
      //Check if JsonProperty annotation is present and if value is set
      if (annotation != null && annotation.value() != null && !annotation.value().isEmpty()) {
        return annotation.value();
      } else {
        return fieldError.getField();
      }
    } catch (Exception e) {
      return fieldError.getField();
    }
  }

此代码可用于在具有@ControllerAdvice的类中处理 BindExceptions @ExceptionHandler(BindException.class)的方法中:

@ControllerAdvice
public class ControllerExceptionHandler {

  @ExceptionHandler(BindException.class)
  public ResponseEntity<YourErrorResultModel> handleBindException(final BindException exception) {
    for (FieldError fieldError : exception.getBindingResult().getFieldErrors()) {
      final String fieldName = getJsonFieldName(fieldError);
   ...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM