raonirenosto
raonirenosto

Reputation: 1515

Spring set default Content-type to "application/json;charset=utf-8" when Jackson is not used

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

Upvotes: 3

Views: 27998

Answers (4)

Alexey Stepanov
Alexey Stepanov

Reputation: 811

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);
    }
}

Upvotes: 3

R.A
R.A

Reputation: 1871

Spring > 4.3.4

@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE)

Upvotes: 5

Frank Lee
Frank Lee

Reputation: 91

modify produces

for example:

@RequestMapping(method = RequestMethod.GET, produces = { "application/json; charset=utf-8" })

public @ResponseBody Object get1() {
...
}

Upvotes: 0

raonirenosto
raonirenosto

Reputation: 1515

@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));
    }
}

Upvotes: 4

Related Questions