我使用最新版本的javax.validation实现了一个简单的验证。
所以我的课:
@Getter
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Person {
@NotNull(message = "Required field")
@JsonAlias(value = "current_name")
private String name;
@NotNull(message = "Required field")
private String age;
}
然后我创建了一个Advice来处理和自定义异常消息。像这样:
@ControllerAdvice
public class CustomRestExceptionHandler extends ResponseEntityExceptionHandler {
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(
MethodArgumentNotValidException ex,
HttpHeaders headers,
HttpStatus status,
WebRequest request) {
List<FieldError> errors = ex.getBindingResult().getFieldErrors();
List<Field> listOfErrors = errors.stream()
.map(error -> Field.builder()
.field(error.getField())
.message(error.getDefaultMessage())
.build())
.collect(Collectors.toList());
ApiError apiError = new ApiError("validation_error", "Some invalid fields", listOfErrors);
return handleExceptionInternal(ex, apiError, headers, HttpStatus.BAD_REQUEST, request);
}
}
因此,当获取error.getField((时,它是一个原始属性名称:"名称";。但我需要得到别名:";current_name";。
我在用杰克逊的利布。
有可能吗?
在handleMethodArgumentNotValid方法中,执行以下
- 查找当前参数类型的所有字段
Field[] clsFields = ex.getParameter().getParameter().getType().getDeclaredFields();
在该字段上查找匹配字段和@JsonAlias注释
读取注释的值-->你在中输入的值是多少
@JsonAlias(value = "current_name")
String name;
- 使用该值而不是原始字段
error.getField()
完整的工作示例:
import com.fasterxml.jackson.annotation.JsonAlias;
import lombok.*;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.*;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.*;
@SpringBootApplication
public class JsonInspect {
public static void main(String[] args) { SpringApplication.run(JsonInspect.class, args); }
}
@RestController
class Controller {
@PostMapping("/test")
public void t(@RequestBody @Valid Person p) {
System.out.println(p);
}
}
@ControllerAdvice
class CustomRestExceptionHandler extends ResponseEntityExceptionHandler {
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
Field[] clsFields = ex.getParameter().getParameter().getType().getDeclaredFields();
List<FieldError> errors = ex.getBindingResult().getFieldErrors();
List<ErrField> listOfErrors = errors.stream()
.map(e -> new ErrField(getJsonAlias(clsFields, e), e.getDefaultMessage()))
.collect(Collectors.toList());
ApiError apiError = new ApiError("validation_error", "Some invalid fields", listOfErrors);
return handleExceptionInternal(ex, apiError, headers, HttpStatus.BAD_REQUEST, request);
}
String getJsonAlias(Field[] clsFields, FieldError e) {
JsonAlias[] alisas = getAnnotationsForField(clsFields, e.getField());
if (alisas == null || alisas.length == 0) {
return e.getField();
}
String[] values = alisas[0].value();
if (values.length == 0) {
return e.getField();
}
return values[0];
}
JsonAlias[] getAnnotationsForField(Field[] clsFields, String fieldName) {
Optional<Field> first = Stream.of(clsFields).filter(f -> f.getName().equals(fieldName)).findFirst();
return first.map(field -> field.getAnnotationsByType(JsonAlias.class)).orElse(null);
}
}
@Data
@AllArgsConstructor
class ErrField {
String fld;
String message;
}
@Data
@AllArgsConstructor
class ApiError {
String type;
String message;
List<ErrField> fields;
}
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Data
class Person {
@JsonAlias("person_name")
@NotNull
String name;
@NotNull
String address;
}
所需库
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>