SpringBoot - Jackson、Gson、fastJson返回JSON數據

一、Jackson

spring-boot-starter-web中默認加入了jackson-databind作爲JSON處理器。在jackson中,對要忽略的屬性上加@JsonIgnore即可,而對於時間進行格式化,則需要在需要格式化的屬性上面加上@JsonFormat註解,並指定格式。

1、創建POJO類

@Data
public class Student {
    /** ID */
    private Long id;
    /** 姓名 */
    private String name;
    /** 性別 */
    private String sex;
    /** 班級 */
    @JsonIgnore  // 忽略傳送給前端
    private String classGrade;
    /** 入學日期 */
    @JsonFormat(pattern = "yyyy-MM-dd")  // 時間格式化
    private Date admissionDate;
}

2、創建Controller層

@RestController
public class StudentController {
    @GetMapping("/student")
    public Student student(){
        Student student = new Student();
        student.setId(1L);
        student.setName("柳成蔭");
        student.setSex("男");
        student.setClassGrade("21班");
        student.setAdmissionDate(new Date());
        return student;
    }
}

3、結果查看

JSON數據

二、Gson

gson是一個JSON的開源解析框架。在SpringBoot中要使用其他的JSON解析框架,因爲spring-boot-starter-web自動引入了jackson-databind,所以需要先移除它。

1、pom依賴

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <!-- 去除默認的jackson -->
    <exclusions>
        <exclusion>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<!-- Gson -->
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
</dependency>

2、配置文件

在寫配置文件前,先對之前的Student類進行修改,去除所有屬性上的註解,並將Sex屬性修改爲protected,這是因爲Gson可以指定被某類修飾符所修飾的屬性進行忽略。
SpringBoot使用Gson可以像jackson一樣,因爲提供了自動轉換類。但是想要對日期進行格式化,需要自己提供自定義的HttpMessagerConverter

@Configuration
public class GsonConfig {
    @Bean
    public GsonHttpMessageConverter gsonHttpMessageConverter(){
        GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
        GsonBuilder builder = new GsonBuilder();
        // 設置解析日期的格式
        builder.setDateFormat("yyyy-MM-dd HH:MM:SS");
        // 過濾修飾符爲protected的屬性
        builder.excludeFieldsWithModifiers(Modifier.PROTECTED);
        Gson gson = builder.create();
        converter.setGson(gson);
        return converter;
    }
}

3、結果查看

JSON

三、fastJson

fastjson是阿里巴巴的一個開源JSON解析框架,是目前JSON解析速度最快的開源框架。同樣,集成fastjson需要去除默認的jacksonfastjson不能像前面兩個框架,在SpringBoot中可以直接使用,它需要我們自己提供一個HttpMessageConverter

1、pom依賴

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <!-- 去除默認的jackson -->
    <exclusions>
        <exclusion>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.28</version>
</dependency>

2、配置文件

fastjson可以自己寫一個config,像上面的gson一樣,提供FastJsonHttpMessageConverter的方法即可,也可以通過實現WebConfigurer接口裏的configureMessageConverters方法來進行配置。

@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        FastJsonConfig config = new FastJsonConfig();
        // 設置日期格式化
        config.setDateFormat("yyyy-MM-dd");
        // 設置數據編碼
        config.setCharset(Charset.forName("UTF-8"));
        config.setSerializerFeatures(
//                SerializerFeature.WriteClassName,        // 在生成JSON中輸出類名(一般都不需要)
                SerializerFeature.WriteMapNullValue,     // 輸出value爲null的數據
                SerializerFeature.PrettyFormat,          // JSON格式化
                SerializerFeature.WriteNullListAsEmpty,  // 集合爲空時,輸出[]
                SerializerFeature.WriteNullStringAsEmpty // String爲空時,輸出""
        );
        converter.setFastJsonConfig(config);
        // 將自定義的FastJsonHttpMessageConvert加入converters中
        converters.add(converter);
    }
}

前面說了,可以通過自己寫的配置類來完成FastJsonHttpMessageConverter

@Configuration
public class MyFastJsonConfig {
	@Bean
	public FastJsonHttpMessageConverter fastJsonHttpMessageConverter(){
		// 將上面方法裏的內容寫到這裏即可
	}
}

其實Gson也是可以通過WebMvcConfigurer接口來做,但是不推薦。因爲,如果項目中沒有GsonHttpMessageConverter,SpringBoot會自己提供一個GsonHttpMessageConverter。這時,我們去重寫configureMessageConverters方法需要替換已有的GsonHttpMessageConverter實例,這是很麻煩的。

3、yml配置文件

使用fastjson,還需要配置響應編碼,如果不配置,可能會導致中文亂碼。

spring:
  http:
    encoding:
      force-response: true       # 響應編碼

4、結果查看

JSON

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章