zoukankan      html  css  js  c++  java
  • 【原创】@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>
  • 相关阅读:
    jar包依赖整理(一)
    centos 下 tomcat 内存不足引起的错误
    KendoUI 基础:Grid 绑定template展示
    C#读取XML文件的五个步骤
    C#winform向Txt文件传值,不重复录入且不清空
    JS页面赋值
    Python3---对象编程思想
    Python3---标准库---numpy
    Python3---标准库json
    Python3---标准库sys
  • 原文地址:https://www.cnblogs.com/mengyi/p/8118826.html
Copyright © 2011-2022 走看看