spring cloud 学习(11) - 用fastson替换jackson及用gb2312码输出

前几天遇到一个需求,因为要兼容旧项目的编码格式,需要spring-cloud的rest接口,输出gb2312编码,本以为是一个很容易的事情,比如下面这样:

    @RequestMapping(method = RequestMethod.POST, value = "syncPaymentList",
            consumes = {"application/json; charset=gb2312"},
            produces = {"application/json; charset=gb2312"})
    public GatewayDataResult syncPaymentList(SyncPaymentListRequest request) {
        ...return ...;
    }

发现只是把输出的response里Content-Type变成了application/json;charset=gb2312,内容本身并没有变化(即:浏览器设置成简体中文,显示乱码)

有一个很简单粗暴的办法,到是可以(参考下面的),但是对原来代码改变太大:

    @RequestMapping(method = RequestMethod.GET, value = "/test")
    public void gb2312Test(HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=gb2312");
        PrintWriter out = response.getWriter();
        out.print("{\"errno\":12,\"errmsg\":\"登录超时\"}");
        return;
    }

另外网有一些办法,比如修改application.yml

spring:
  http:
    encoding:
      enabled: true
      charset: GB2312
      force: true  

相当于传统spring-mvc中下面这段配置

    <filter>
        <filter-name>CharacterEncodingFilterfilter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
        <init-param>
            <param-name>encodingparam-name>
            <param-value>gb2312param-value>
        init-param>
        <init-param>
            <param-name>forceEncodingparam-name>
            <param-value>trueparam-value>
        init-param>
    filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>

发现也没用,然后看了下jackson2的源码,com.fasterxml.jackson.core.JsonEncoding这个类,默认就只支持UTF-8/16编码,要支持其它编码的话

spring cloud 学习(11) - 用fastson替换jackson及用gb2312码输出_第1张图片

得自己扩展JsonGenerator,写一堆代码,太复杂,参考:https://stackoverflow.com/questions/10004241/jackson-objectmapper-with-utf-8-encoding

最后想起了以前dubbo中用fastjson替换jackson时,解决过类似问题(参考 dubbox REST服务使用fastjson替换jackson) ,发现了一个很简单的办法,拿fastjson替换jackson2,只要注入下面这个bean就可以了:

 1     @Bean
 2     public HttpMessageConverters fastJsonHttpMessageConverters() {
 3         FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
 4         FastJsonConfig fastJsonConfig = new FastJsonConfig();
 5         fastJsonConfig.setSerializerFeatures(SerializerFeature.DisableCircularReferenceDetect);
 6         fastJsonConfig.setCharset(Charset.forName("gb2312"));
 7 
 8         List fastMediaTypes = new ArrayList<>();
 9         fastMediaTypes.add(MediaType.APPLICATION_JSON);
10         fastConverter.setSupportedMediaTypes(fastMediaTypes);
11 
12         fastConverter.setFastJsonConfig(fastJsonConfig);
13         HttpMessageConverter converter = fastConverter;
14         return new HttpMessageConverters(converter);
15     }

你可能感兴趣的:(spring cloud 学习(11) - 用fastson替换jackson及用gb2312码输出)