SpringBoot集成FastJsonHTTP消息转换器

概述

使用fastjson作为Springboot的HttpMessageConverter,即在Web中返回@ResponseBody时使用的将对象、集合等转为Json的转换器.

  1. 在maven中添加依赖
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.58</version>
</dependency>
  1. 在配置中添加一个HttpMessageConverters的Bean
@Bean
public HttpMessageConverters fastJsonHttpMessageConverter()
{
    //使用FastJson作为HTTP的序列换和反序列工具
    // 1.定义Converter转换器对象
    FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
    // 2.1设置转换器的配置信息
    FastJsonConfig config = new FastJsonConfig();
    config.setSerializerFeatures(SerializerFeature.WriteNullStringAsEmpty);
    // 2.2设置编码,处理中文乱码
    converter.setDefaultCharset(Charset.forName("UTF-8"));
    config.setCharset(Charset.forName("UTF-8"));
    // 3.将设置添加到转换器中
    converter.setFastJsonConfig(config);
    // 4.将转换器转为HttpMessageConverter并返回
    HttpMessageConverter<Object> ret = converter;
    return new HttpMessageConverters(ret);
}
  1. 完成配置

相关知识

SerializerFeatures常用枚举

  • WriteNullListAsEmpty:List字段如果为null,输出为[],而非null
  • WriteNullStringAsEmpty:字符类型字段如果为null,输出为"",而非null
  • DisableCircularReferenceDetect:消除对同一对象循环引用的问题,默认为false(如果不配置有可能会进入死循环)
  • WriteNullBooleanAsFalse:Boolean字段如果为null,输出为false,而非null
  • WriteMapNullValue:是否输出值为null的字段,默认为false
  • PrettyFormat:有以上的特性,也就是以漂亮格式进行转换
发布了10 篇原创文章 · 获赞 2 · 访问量 785

猜你喜欢

转载自blog.csdn.net/u011618818/article/details/105627955
今日推荐