I'm implementing ResponseEntityExceptionHandler and when an exception is thrown I want the ResponseEntity body to include unicode codes for special characters, for example '<' will be '\<'
However, when trying to escape the unicode I'm getting an extra backslash in the response.
This is my class:
@ControllerAdvice
public class DefaultErrorHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler({Exception.class})
public ResponseEntity<Map> applicationExceptionHandler(Exception ex, WebRequest request) {
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE);
Map<String,Object> map = new HashMap<>();
map.put("message", "\\u003CI'm a string between <>\\u003E");
return ResponseEntity.ok().headers(responseHeaders).body(map);
}
}
This code returns
{"message":"\\u003CI'm a string between <>\\u003E"}
If I write
map.put("message", "\u003CI'm a string between <>\u003E");
then I get
{"message":"<I'm a string between <>>"}
And what I want is
{"message":"\u003CI'm a string between <>\u003E"}
Is there any way to escape correctly the unicode using a ResponseEntity?
JSON specification says that every '\\uxxxx' character in a string is treated as a unicode character, that's why they are escaped. If you parse the output and print message
field there should be single backslashes.
> JSON.parse(out).message
"\u003CI'm a string between <>\u003E"
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.