I would like to change my spring app default "Content-type" to "application/json;charset=utf-8" instead of only "application/json"
Asked
Active
Viewed 2.4k times
3
-
Is there a specific reason for that? The default encoding for JSON is UTF-8. – Guffa Aug 12 '14 at 22:49
-
I'm not using Jackson. My controllers are returning ResponseEntity
, so "application/text" by default. – raonirenosto Aug 12 '14 at 22:54
4 Answers
4
@Configuration
@EnableWebMvc
public class MVCConfig extends WebMvcConfigurerAdapter {
@Override
public void configureContentNegotiation(
ContentNegotiationConfigurer configurer) {
final Map<String, String> parameterMap = new HashMap<String, String>();
parameterMap.put("charset", "utf-8");
configurer.defaultContentType(new MediaType(
MediaType.APPLICATION_JSON, parameterMap));
}
}

raonirenosto
- 1,507
- 5
- 19
- 30
-
3You can use new MediaType(MediaType.APPLICATION_JSON, Collections.singletonMap("charset", "utf-8")) or new MediaType("application", "json" , Charset.forName("utf-8")). In new Spring there is MediaType.APPLICATION_JSON_UTF8 – Maksim Maksimov Aug 30 '16 at 11:19
-
1Also in Spring 4.3+ you can do `new MediaType(MediaType.APPLICATION_JSON, StandardCharsets.UTF_8);` – Ruslan Stelmachenko Jan 26 '18 at 19:57
3
The simplest solution for default content type charset, that I found, by using a request filter:
@Component
public class CharsetRequestFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
filterChain.doFilter(request, response);
}
}

Alexey Stepanov
- 561
- 6
- 15
0
modify produces
for example:
@RequestMapping(method = RequestMethod.GET, produces = { "application/json; charset=utf-8" })
public @ResponseBody Object get1() {
...
}

Frank Lee
- 81
- 1
- 4