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

时间:2023-03-09 17:18:09
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<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编码,要支持其它编码的话

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

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

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

     @Bean
public HttpMessageConverters fastJsonHttpMessageConverters() {
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.DisableCircularReferenceDetect);
fastJsonConfig.setCharset(Charset.forName("gb2312")); List<MediaType> fastMediaTypes = new ArrayList<>();
fastMediaTypes.add(MediaType.APPLICATION_JSON);
fastConverter.setSupportedMediaTypes(fastMediaTypes); fastConverter.setFastJsonConfig(fastJsonConfig);
HttpMessageConverter<?> converter = fastConverter;
return new HttpMessageConverters(converter);
}