1. 程式人生 > >十一、Spring Boot完美使用FastJson解析JSON資料

十一、Spring Boot完美使用FastJson解析JSON資料

  Spring Boot集成了Jackson框架來處理JSON資料,但目前FastJson框架是處理JSON資料最高效的框架,如何替換Jackson框架,步驟如下:

(一)新增依賴

<!--spring boot預設的json工具是jackson,因為fastjson更快,所以這裡需要替換成fastjson-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId
>
<version>1.2.28</version> </dependency>

(二)在應用程式啟動類中,新增如下程式碼:

/**
 * @SpringBootApplicatio: 指定這是一個Spring boot應用程式
 */
@SpringBootApplication
public class SbHelloApplication {

    public static void main(String[] args) {
        //在main方法中啟動應用程式
        SpringApplication.run(SbHelloApplication.class, args);
    }

    /**
     * 使用@Bean註解注入第三方的解析框架(fastJson)
     */
@Bean public HttpMessageConverters fastJsonHttpMessageConverters(){ //1、首先需要先定義一個convert轉換訊息物件 FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter(); //2、新增fastJson的配置資訊,比如:是否要格式化返回的json資料 FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat); //3、在convert中新增配置資訊
fastConverter.setFastJsonConfig(fastJsonConfig); return new HttpMessageConverters(fastConverter); } }

(三)使用

public class User {
    private Integer id;
    private String username;
    private Integer age;
    /**
     * fastJson特性:格式化
     */
    @JSONField(format = "yyyy-MM-dd HH:mm")
    private Date createTime;
    /**
     * 不輸出該成員變數,相當於Jackson的@JsonInclude註解
     * serialize:是否需要序列化
     */
    @JSONField(serialize = false)
    private String remark;
}