spring boot -- 控制器类中方法返回对象json序列化

前言

  fastjson是一个Java语言编写的高性能功能完善的JSON库。它采用一种“假定有序快速匹配”的算法,把JSON Parse的性能提升到极致,是目前Java语言中最快的JSON库。Fastjson接口简单易用,已经被广泛使用在缓存序列化、协议交互、Web输出、Android客户端

   Jackson:是spring boot 默认的解析和序列化json数据的库,作用和fastjson一样,只不过阿里的fastjson的性能要比jackson好些,大多数人的选择都是fastjson

引入依赖

   <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.56</version>
    </dependency>

JSON class

  引入依赖后,会提供一个JSON类,它有很多比较高效和实用的方法

 

定义控制器返回对象json序列化处理器

  全局替换spring boot 默认的控制器返回对象序列化处理器。控制器中的方法返回的对象,spring boot都会对它进行一个序列化处理,后才会返回给前端,默认的处理器是JackSon

@Configuration
public class CustomMVCConf extends WebMvcConfigurationSupport {

@Override protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) { /* 先把JackSon的消息转换器删除. 备注: (1)源码分析可知,返回json的过程为: Controller调用结束后返回一个数据对象,for循环遍历 Converter,找到支持application/json的HttpMessageConverter,然后将返回的数据序列化成json。 具体参考org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor的writeWithMessageConverters方法 (2)由于是list结构,我们添加的fastjson在最后。因此必须要将jackson的转换器删除,不然会先匹配上jackson,导致没使用fastjson */ for (int i = converters.size() - 1; i >= 0; i--) { if (converters.get(i) instanceof MappingJackson2HttpMessageConverter) { converters.remove(i); } } FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter(); //自定义fastjson配置 FastJsonConfig config = new FastJsonConfig(); config.setSerializerFeatures( SerializerFeature.WriteMapNullValue, // 是否输出值为null的字段,默认为false,我们将它打开 SerializerFeature.WriteNullListAsEmpty, // 将Collection类型字段的字段空值输出为[] SerializerFeature.WriteNullStringAsEmpty, // 将字符串类型字段的空值输出为空字符串 SerializerFeature.WriteNullNumberAsZero, // 将数值类型字段的空值输出为0 SerializerFeature.WriteDateUseDateFormat, SerializerFeature.DisableCircularReferenceDetect // 禁用循环引用 ); fastJsonHttpMessageConverter.setFastJsonConfig(config); // 添加支持的MediaTypes;不添加时默认为*/*,也就是默认支持全部 // 但是MappingJackson2HttpMessageConverter里面支持的MediaTypes为application/json // 参考它的做法, fastjson也只添加application/json的MediaType List<MediaType> fastMediaTypes = new ArrayList<>(); fastMediaTypes.add(MediaType.APPLICATION_JSON); fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes); converters.add(fastJsonHttpMessageConverter); super.configureMessageConverters(converters); } }
原文地址:https://www.cnblogs.com/wrhbk/p/15166435.html