简体   繁体   中英

Return @JsonAlias value in ControllerAdvice Method Argument Validation (@Valid) response

I has implemented a simple validation using javax.validation, latest version.

So my class:

@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;
}

And then I created a Advice to handle and customize the exception message. Like this:

@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);
    }
}

So, when a get the error.getField() , It is a original attribute name: "name". But I need to get the alias: "current_name".

I'm using Jackson lib.

It's possible?

In your handleMethodArgumentNotValid method, do the following

  1. Find all the fields for current parameter type
    Field[] clsFields = ex.getParameter().getParameter().getType().getDeclaredFields();
  1. Find matching Field and @JsonAlias annotations on that field

  2. Read value of the annotation --> which is the value that you put in

 @JsonAlias(value = "current_name")
 String name;
  1. Use that value instead of the original field error.getField()

Complete working example:

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;
}

Required libraries

    <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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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