SpringMVC使用ResponseBody返回json时中文乱码

在SpringMVC中的Controller中,返回非String类时,不会遇到这种情况。但返回为String时,中文有可能会变成乱码。

1
2
3

public class StringHttpMessageConverter extends AbstractHttpMessageConverter<String> {
public static final Charset DEFAULT_CHARSET = Charset.forName("ISO-8859-1");

转换器的默认编码是ISO-8859-1,而非UTF-8。

解决办法

  1. 使用(produces = “application/json; charset=utf-8”)
1
2
3
4
@RequestMapping(value = "/xxx", produces = "produces=MediaType.APPLICATION_JSON_VALUE + ";charset=utf-8")
@ResponseBody
public String fun() {
}
  1. 在spring-mvc.xml中添加:
1
2
3
4
5
6
7
8
9
10
11
12
<!-- 处理请求返回json字符串的中文乱码问题 -->
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>