JSON charset handling in StringHttpMessageConverter

This commit restores the interpretation of JSON as UTF-8 by default that
was removed in #bc205e0 and also ensures a charset is not appended
automatically to "application/json".

Closes gh-24123
This commit is contained in:
Rossen Stoyanchev
2019-12-10 16:37:31 +00:00
parent 70a0c93d69
commit 9b30d46ff4
3 changed files with 40 additions and 2 deletions

View File

@@ -100,6 +100,18 @@ public class StringHttpMessageConverter extends AbstractHttpMessageConverter<Str
return (long) str.getBytes(charset).length;
}
@Override
protected void addDefaultHeaders(HttpHeaders headers, String s, @Nullable MediaType mediaType) throws IOException {
if (headers.getContentType() == null ) {
if (mediaType != null && mediaType.isCompatibleWith(MediaType.APPLICATION_JSON)) {
// Prevent charset parameter for JSON..
headers.setContentType(mediaType);
}
}
super.addDefaultHeaders(headers, s, mediaType);
}
@Override
protected void writeInternal(String str, HttpOutputMessage outputMessage) throws IOException {
HttpHeaders headers = outputMessage.getHeaders();
@@ -130,6 +142,10 @@ public class StringHttpMessageConverter extends AbstractHttpMessageConverter<Str
if (contentType != null && contentType.getCharset() != null) {
return contentType.getCharset();
}
else if (contentType != null && contentType.isCompatibleWith(MediaType.APPLICATION_JSON)) {
// Matching to AbstractJackson2HttpMessageConverter#DEFAULT_CHARSET
return StandardCharsets.UTF_8;
}
else {
Charset charset = getDefaultCharset();
Assert.state(charset != null, "No default charset");