文章出處

前幾天遇到一個需求,因為要兼容舊項目的編碼格式,需要spring-cloud的rest接口,輸出gb2312編碼,本以為是一個很容易的事情,比如下面這樣:

    @RequestMapping(method = RequestMethod.POST, value = "syncPaymentList",
            consumes = {"application/json; charset=gb2312"},
            produces = {"application/json; charset=gb2312"})
    public GatewayDataResult<DcbOrderListResponse> 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>CharacterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>gb2312</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

發現也沒用,然后看了下jackson2的源碼,com.fasterxml.jackson.core.JsonEncoding這個類,默認就只支持UTF-8/16編碼,要支持其它編碼的話

得自己擴展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<MediaType> 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     }

文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()