简体   繁体   English

spring如何让json响应统一格式?

[英]How to make json response Unified format in spring?

I want all json response is我想要所有的 json 响应是

{
   "status":"ok"
    "data":"..."
}

I only care @ResponseBody function return value;Don't need wrap any object to do it;我只关心@ResponseBody 函数的返回值;不需要包装任何对象来做;

example:例子:

@ResponseBody
public String test(){
   return "Hello,World"
}

I want get我想得到

{
   "status":"ok"
    "data":"Hello,World"
}

You must return a Object instead of String for example :您必须返回一个对象而不是字符串,例如:

public class CustomResponse {
  private String status;
  private String data;

  // Getters & Setters
}

@ResponseBody
public CustomResponse test(){
    CustomResponse response = new CustomResponse();

    response.setStatus("OK");
    response.setData("Hello,World");

    return response;
}

I thought it is not a good solution but you can format string我认为这不是一个好的解决方案,但您可以格式化字符串

@RequestMapping(value="testData")
public @ResponseBody String testData(){
    String sdata="ok";
    String value ="Hello,World";

    return "{\"status\" :\""+sdata+"\",\"data \":\""+value+"\"}";
}

I found this solve problem.我发现这解决了问题。 rewrite default RequestResponseBodyMethodProcessor can wrap any object to return value重写默认 RequestResponseBodyMethodProcessor 可以包装任何对象以返回值

ResponseBodyAdvice can do it.you can implement the interface to handle ReqeustBody. ResponseBodyAdvice可以做到。你可以实现接口来处理 ReqeustBody。 Here is the api .这是api In the documents.在文件中。

Allows customizing the response after the execution of an @ResponseBody or a ResponseEntity controller method but before the body is written with an HttpMessageConverter.允许在执行 @ResponseBody 或 ResponseEntity 控制器方法之后但在使用 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.实现可以直接使用 RequestMappingHandlerAdapter 和 ExceptionHandlerExceptionResolver 注册,或者更有可能使用 @ControllerAdvice 进行注释,在这种情况下,它们将被两者自动检测。

here is a simple code.这是一个简单的代码。

@ControllerAdvice
public customerResponseBody implements ResponseBodyAdvice{
    @Override
    public boolean supports (MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType){
        return true;
    }

    @Override  
    public Object beforeBodyWrite (Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response){
        body = new ResponseTemplate<Object>("001",body);
        return body;
    }
}

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

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