【原创】@ResponseBody返回json数据时出现中文乱码

ι 版权声明:本文为博主原创文章,未经博主允许不得转载。

 

原因:

Spring中解析字符串的转换器默认编码格式是ISO-8859-1

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

 

2种解决方案:

方案一:使用@RequestMapping注解的produces方法,设置produces = "application/json; charset=utf-8"

示例代码:

@RequestMapping(value="/weather",produces = "application/json;charset=utf-8")
@ResponseBody
public String weather() throws Exception{
  String url = "http://www.weather.com.cn/data/cityinfo/101271001.html";
  String weatherData = HttpClientHelper.sendGet(url, null, "utf-8");
  return weatherData;
}

方案二:在spring-servlet.xml中配置StringHttpMessageConverter的值

<mvc:annotation-driven>
   <mvc:message-converters>  
    <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>  
    <bean class="org.springframework.http.converter.StringHttpMessageConverter">  
       <property name="supportedMediaTypes">  
          <list>  
              <value>text/plain;charset=utf-8</value>  
              <value>text/html;charset=UTF-8</value>  
          </list>  
       </property>  
    </bean>  
  </mvc:message-converters>  
</mvc:annotation-driven>

 

posted @ 2017-12-26 16:51  Bella的技术轮子  阅读(579)  评论(0编辑  收藏  举报