springboot(五)使用FastJson返回Json視圖


FastJson簡介:

   fastJson是阿里巴巴旗下的一個開源項目之一,顧名思義它專門用來做快速操作Json的序列化與反序列化的組件。它是目前json解析最快的開源組件沒有之一!在這之前jaskJson是命名為快速操作json的工具,而當阿里巴巴的fastJson誕生后jaskjson就消聲匿跡了,不過目前很多項目還在使用。
 
本文目標:
   將fastJson加入到SpringBoot項目內,配置json返回視圖使用fastJson解析。
 

一、項目搭建

  項目搭建目錄及數據庫

二、添加依賴(FastJson依賴)

  spring-boot-stater-tomcat依賴的scope屬性一定要注釋掉,我們才能在IntelliJ IDEA工具使用SpringBootApplication的形式運行項目!

  依賴地址:mvnrepository.com/artifact/com.alibaba/fastjson/1.2.31

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.dyh</groupId>
    <artifactId>lesson_three</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>lesson_three</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <!--<scope>provided</scope>-->
        </dependency>

        <dependency>
            <!--fastJson-->
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.51</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
View Code

 

三、配置文件(該項目用Spring Data JPA架構)

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT
    driverClassName: com.mysql.cj.jdbc.Driver
    username: root
    password: root

  jpa:
    database: MySQL
    show-sql: true
    hibernate:
#      naming_strategy: org.hibernate.cfg.ImprovedNamingStrategy
#      ddl-auto: create
View Code

 

四、創建一個FastJsonConfiguration配置信息類。

  添加@Configuration注解讓SpringBoot自動加載類內的配置,有一點要注意我們繼承了WebMvcConfigurerAdapter這個類,這個類是SpringBoot內部提供專門處理用戶自行添加的配置,里面不僅僅包含了修改視圖的過濾還有其他很多的方法,包括我們后面章節要講到的攔截器,過濾器,Cors配置等。

@Configuration
public class FastJsonConfiguration extends WebMvcConfigurerAdapter
{
    /**
     * 修改自定義消息轉換器
     * @param converters 消息轉換器列表
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        //調用父類的配置
        super.configureMessageConverters(converters);
        //創建fastJson消息轉換器
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        //創建配置類
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        //修改配置返回內容的過濾
        fastJsonConfig.setSerializerFeatures(
                SerializerFeature.DisableCircularReferenceDetect,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty
        );
        fastConverter.setFastJsonConfig(fastJsonConfig);
        //將fastjson添加到視圖消息轉換器列表內
        converters.add(fastConverter);
    }
}

FastJson SerializerFeatures

WriteNullListAsEmpty  :List字段如果為null,輸出為[],而非null
WriteNullStringAsEmpty : 字符類型字段如果為null,輸出為"",而非null
DisableCircularReferenceDetect :消除對同一對象循環引用的問題,默認為false(如果不配置有可能會進入死循環)
WriteNullBooleanAsFalse:Boolean字段如果為null,輸出為false,而非null
WriteMapNullValue:是否輸出值為null的字段,默認為false。

 

五、測試,並比較用了FastJson與沒有用之間的比較

 

使用前:

 

 使用后:

name的值從NULL變成了"",那么證明我們的fastJson消息的轉換配置完美生效了

 

 


 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM