I have text in json format and I want send it to the client as json format. I searched around and found that converting it into java object and then returning it is working fine. Can I avoid this process of serialization & deserialization anyhow. I also tried adding @ResponseBody and it did not work.
Current exception handler code:
@ExceptionHandler({CustomRuntimeException.class})
@ResponseBody
public Object handleRuntimeException(CustomRuntimeException exception) {
String jsonString = exception.getResponseJson();
ObjectMapper objectMapper = new ObjectMapper();
Object response = objectMapper.readValue(jsonString, CustomResponse.class);
return response;
}
CodePudding user response:
You can always use ResponseEntity
with content type of json, now the text should be properly parsed by the client based on this.
@ExceptionHandler({CustomRuntimeException.class})
@ResponseBody
public Object handleRuntimeException(CustomRuntimeException exception) {
String jsonString = exception.getResponseJson();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
return new ResponseEntity<Object>(responseBody, headers, HttpStatus.BAD_REQUEST);
}