今天遇到一个bug,fastJSON在将Map转换为字符串的时候,会出现当KEY为Long类型时,转换出来的字符串不为json格式。如:
Map<Integer, String> m = new HashMap<>();
m.put(1,"1");
m.put(2,"2");
序列化结果为:
{1:"1",2:"2"}
不是我想要的。
查询了如下链接
https://github.com/alibaba/fastjson/issues/294
发现可以通过如下代码解决这个问题。
Map<Integer, String> m = new HashMap<>();
m.put(1, "1");
m.put(2, "2");
JSON.toJSONString(m, new NameFilter() {
@Override
public String process(Object object, String name, Object value) {
return name;
}
});
然而我想在SpringBoot中修改FastJson全局序列化的模式,就要修改如下代码,有很多方式进行配置,都差不多。直接给出一种答案:
继承WebMvcConfigurerAdapter
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
/**
* 初始化启动注册日志
*/
private static final Logger log = LOG.COMMON_LOG;
/**
* 手动配置过滤器
* @return
*/
@Bean
public FilterRegistrationBean someFilterRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(sessionFilter());
registration.addUrlPatterns("/*");
registration.addInitParameter("paramName", "paramValue");
registration.setName("baseFilter");
return registration;
}
/**
* 手动创建一个bean
* @return
*/
@Bean(name = "baseFilter")
public Filter sessionFilter() {
return new BaseFilter();
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
super.configureMessageConverters(converters);
{
StringHttpMessageConverter messageConverter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
List<MediaType> mediaTypeList = new ArrayList<MediaType>();
mediaTypeList.add(MediaType.TEXT_PLAIN);
messageConverter.setSupportedMediaTypes(mediaTypeList);
converters.add(messageConverter);
log.info("注册 HTTP 字符串消息转换器: {}", messageConverter.getSupportedMediaTypes());
}
{
FastJsonHttpMessageConverter messageConverter = new FastJsonHttpMessageConverter();
FastJsonConfig config = new FastJsonConfig();
config.setSerializerFeatures(SerializerFeature.PrettyFormat,SerializerFeature.DisableCircularReferenceDetect);
// 这里设置了序列化的Filter,加入了NameFilter的实现,将Long型的key进行修改,加上引号
config.setSerializeFilters((NameFilter) (object, name, value) -> name);
messageConverter.setFastJsonConfig(config);
messageConverter.setDefaultCharset(Charset.forName("UTF-8"));
List<MediaType> mediaTypeList = new ArrayList<>();
mediaTypeList.add(MediaType.APPLICATION_JSON);
mediaTypeList.add(MediaType.APPLICATION_JSON_UTF8);
messageConverter.setSupportedMediaTypes(mediaTypeList);
converters.add(messageConverter);
log.info("HTTP JSON 消息转换器特性: {}", ArrayUtil.toString(Util.getJsonFeature()));
log.info("注册 HTTP JSON 消息转换器: {}", messageConverter.getSupportedMediaTypes());
}
}
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
configurer.setUseTrailingSlashMatch(false);
configurer.setUseRegisteredSuffixPatternMatch(false);
configurer.setUseSuffixPatternMatch(false);
}
}
在fastJson的官方github上也可以查找到相关线索:
https://github.com/alibaba/fastjson/wiki/%E5%AE%9A%E5%88%B6%E5%BA%8F%E5%88%97%E5%8C%96
总结:
fastJson和Spring都预留了扩展点,可供我们定制化自己的东西,还是很🐮🍺的。^-^