zoukankan      html  css  js  c++  java
  • 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); } }
  • 相关阅读:
    String类型作为方法的形参
    [转] 为什么说 Java 程序员必须掌握 Spring Boot ?
    Centos打开、关闭、结束tomcat,及查看tomcat运行日志
    centos中iptables和firewall防火墙开启、关闭、查看状态、基本设置等
    防火墙没有关导致外部访问虚拟机的tomcat遇到的问题和解决方法
    可以ping通ip地址,但是访问80,或者8080报错
    JAVA的非对称加密算法RSA——加密和解密
    CA双向认证的时候,如果一开始下载的证书就有问题的,怎么保证以后的交易没有问题?
    图解HTTPS协议加密解密全过程
    https单向认证服务端发送到客户端到底会不会加密?
  • 原文地址:https://www.cnblogs.com/wrhbk/p/15166435.html
Copyright © 2011-2022 走看看