3

I would like to change my spring app default "Content-type" to "application/json;charset=utf-8" instead of only "application/json"

raonirenosto
  • 1,507
  • 5
  • 19
  • 30

4 Answers4

6

Spring > 4.3.4

@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
R.A
  • 1,813
  • 21
  • 29
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
  • 3
    You 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
  • 1
    Also 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