1. 程式人生 > >(4)Spring Boot完美使用FastJson解析JSON資料【從零開始學Spring Boot】

(4)Spring Boot完美使用FastJson解析JSON資料【從零開始學Spring Boot】

個人使用比較習慣的json框架是fastjson,所以spring boot預設的json使用起來就很陌生了,所以很自然我就想我能不能使用fastjson進行json解析呢?

引入fastjson依賴庫:

  <dependencies>

        <dependency>

           <groupId>com.alibaba</groupId>

           <artifactId>fastjson</artifactId>

           <version>1.2.15</version

>

    </dependency>

       這裡要說下很重要的話,官方文件說的1.2.10以後,會有兩個方法支援HttpMessageconvert,一個是FastJsonHttpMessageConverter,支援4.2以下的版本,一個是FastJsonHttpMessageConverter4支援4.2以上的版本,具體有什麼區別暫時沒有深入研究。這裡也就是說:低版本的就不支援了,所以這裡最低要求就是1.2.10+。

配置fastjon

支援兩種方法:

第一種方法就是:

(1)啟動類繼承extends WebMvcConfigurerAdapter

(2)覆蓋方法configureMessageConverters

具體程式碼如下:

/**

 *

 * @author Angel --守護天使

 * @version v.0.1

 * @date 2016729下午7:06:11

 */

@SpringBootApplication

public class ApiCoreApp  extends WebMvcConfigurerAdapter {

    @Override

    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {

        super.configureMessageConverters(converters

);

        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();

        FastJsonConfig fastJsonConfig = new FastJsonConfig();

        fastJsonConfig.setSerializerFeatures(

                SerializerFeature.PrettyFormat

        );

        fastConverter.setFastJsonConfig(fastJsonConfig);

        converters.add(fastConverter);

    }

}

第二種方法:

(1)在App.java啟動類中,注入Bean : HttpMessageConverters

具體程式碼如下:

package com.kfit;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.boot.autoconfigure.web.HttpMessageConverters;

import org.springframework.context.annotation.Bean;

import org.springframework.http.converter.HttpMessageConverter;

import com.alibaba.fastjson.serializer.SerializerFeature;

import com.alibaba.fastjson.support.config.FastJsonConfig;

import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;

/**

 *

 * @author Angel --守護天使

 * @version v.0.1

 * @date 2016729下午7:06:11

 */

@SpringBootApplication

public class ApiCoreApp {

    @Bean

    public HttpMessageConverters fastJsonHttpMessageConverters() {

       FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();

       FastJsonConfig fastJsonConfig = new FastJsonConfig();

       fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);

       fastConverter.setFastJsonConfig(fastJsonConfig);

       HttpMessageConverter<?> converter = fastConverter;

       return new HttpMessageConverters(converter);

    }

    public static void main(String[] args) {

       SpringApplication.run(ApiCoreApp.classargs);

    }

}

       那麼這時候在實體類中使用@JSONField(serialize=false),是不是此欄位就不返回了,如果是的話,那麼恭喜你配置成功了,其中JSONField的包路徑是:com.alibaba.fastjson.annotation.JSONField。