Issue
I need to send differend jsons which depend on the response code.
@ApiOperation(value = "saveObject", nickname = "saveObject", httpMethod = "POST")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Success"),
@ApiResponse(code = 404, message = "Not Found"),
@ApiResponse(code = 500, message = "Failure")})
@PostMapping(value = "/save")
public void saveUser(@RequestBody ObjectView object) {
objectService.saveObject(object);
}
Example: if code is 200 this should send
data: {
“result”:”success”
}
if 500
data: {
“error”:”500”
}
How can I do it with ResponseBodyAdvice
?
@RestControllerAdvice
public class ResponseView implements ResponseBodyAdvice<Object> {
@Override
public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
return true;
}
@Override
public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType,
Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest,
ServerHttpResponse serverHttpResponse) {
return new WrapperObj<Object>(o);
}
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
@JsonSerialize
private class WrapperObj<T> {
private final Object data;
public WrapperObj(Object data) {
this.data = data;
}
}
}
Solution
I did it like this:
import org.springframework.http.HttpStatus;
public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
HttpServletResponse servletResponse = ((ServletServerHttpResponse) serverHttpResponse).getServletResponse();
if(servletResponse.getStatus() == 200) {
return createYourResponseBodyE_G_200().getBody();
} else if(servletResponse.getStatus() == 500) {
return createYourResponseBodyE_G_500().getBody();
}
public ResponseEntity<Object> createYourResponseBodyE_G_200() {
return new ResponseEntity<Object>( "data: { \"result\":\"success\" }", HttpStatus.OK);
}
public ResponseEntity<Object> createYourResponseBodyE_G_500() {
return new ResponseEntity<Object>( "data: { \"error\":\"500\" }", HttpStatus.INTERNAL_SERVER_ERROR);
}
Answered By - John