JSON 我所有 REST 中的自定义响应 API,我可能不知道它叫什么?

JSON Custom response in all my REST API, I might not know what it is called?

所以问题是这样的,对于我所有的 REST API 端点,我的 RESPONSE Body 中应该总是有 3 个字段,例如:

{
 "status": "SUCCESS",
 "message": "A list of a recent post",
 "data" : [LIST OF POSTS]
}

{
"status" : "NOT_AUTHORIZED",
"message": "User does not have previledge to access this resource",
"errors": ["User does not have Admin access"]
}

所以你可以明白,我希望这个消息状态错误或数据字段出现在我的 REST 中的所有响应中 API。

您可以将过滤器添加到您的项目中,并在发送响应之前将其添加到响应中。

按照 创建过滤器。

可以用 ResponseBodyAdvice:

Allows customizing the response after the execution of an @ResponseBody or a ResponseEntity controller method but before the body is written with an HttpMessageConverter.

Implementations may be registered directly with RequestMappingHandlerAdapter and ExceptionHandlerExceptionResolver or more likely annotated with @ControllerAdvice in which case they will be auto-detected by both.

所以你可以有这样的东西:

@ControllerAdvice
public class MyResponseBodyAdvisor implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType,
                            Class<? extends HttpMessageConverter<?>> converterType) {

        return converterType.isAssignableFrom(MappingJackson2HttpMessageConverter.class);
    }

    @Override
    public Object beforeBodyWrite(Object body,
                                  MethodParameter returnType,
                                  MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request,
                                  ServerHttpResponse response) {

        MyResponseWrapper wrapper = new MyResponseWrapper();
        wrapper.setData(body);
        return wrapper;
    }
}

其中 MyResponseWrapper 是您用来包装响应负载的 class。

您可以使用 ResponseBodyAdvice<T> 在响应 POJO 编组到 JSON 之前全局拦截它,但这似乎不合适,因为您的每个 REST 方法都应该根据方法的功能。此外,这无论如何都会迫使您使用一些包装器 class 进行响应。

所以,我想,最好在每个方法中手动将数据(连同状态和消息)包装到响应中