精通 Spring Boot 系列 05

Spring Boot 處理 JSON 數(shù)據(jù)
JSON 是目前主流的前后端數(shù)據(jù)傳輸方式,當(dāng) Controller 中返回的是一個(gè) Java 對(duì)象或 List 集合時(shí),Spring Boot 將自動(dòng)把它轉(zhuǎn)換成 JSON 數(shù)據(jù)。
Spring Boot 中內(nèi)置了 JSON 解析功能,當(dāng)你在項(xiàng)目中,添加了 spring-boot-starter-web 模塊之后,即可看到默認(rèn)包含 Jackson 解析器,也可以換成 Fastjson 等其他解析器。
1. 編輯 Book 類(lèi)
public?class?Book?{
????private?Integer?id;
????private?String?name;
????private?String?author;
????@JsonIgnore
????private?Float?price;
????@JsonFormat(pattern?=?"yyyy-MM-dd")
????private?Date?bookPublicationDate;
????//?getter?和?setter?方法
}
2. 編輯 BookController?
返回?cái)?shù)據(jù)的時(shí)候,需要使用 @ResponseBody 注解。如果經(jīng)常使用 @Controller 和 @ResponseBody 注解,則可以使用 @RestController 組合注解來(lái)替代。
@RestController
public?class?BookController?{
????@GetMapping("/book")
????public?Book?book(){
????????Book?book?=?new?Book();
????????book.setId(1);
????????book.setName("《碼農(nóng)翻身:用故事給技術(shù)加點(diǎn)料》");
????????book.setAuthor("劉欣");
????????book.setPrice(69f);
????????book.setBookPublicationDate(new?Date());
????????return?book;
????}
}
運(yùn)行之后,直接地址欄中訪問(wèn) http://localhost:8080/book,即可看到返回的 JSON 數(shù)據(jù)。

3. 轉(zhuǎn)換集合數(shù)據(jù)
添加 getBooks() 方法,創(chuàng)建一個(gè) List 集合,存放三本書(shū)。具體源碼如下:
@RequestMapping("/getBooks")
public?List?getBooks()? {
????List?bookList?=?new?ArrayList<>();
????Book?book1?=?new?Book();
????book1.setId(1);
????book1.setName("《碼農(nóng)翻身:用故事給技術(shù)加點(diǎn)料》");
????book1.setAuthor("劉欣");
????book1.setPrice(69f);
????book1.setBookPublicationDate(new?Date());
????Book?book2?=?new?Book();
????book2.setId(2);
????book2.setName("《漫畫(huà)算法:小灰的算法之旅(全彩)》");
????book2.setAuthor("魏夢(mèng)舒");
????book2.setPrice(79f);
????book2.setBookPublicationDate(new?Date());
????Book?book3?=?new?Book();
????book3.setId(3);
????book3.setName("《未來(lái)架構(gòu)》");
????book3.setAuthor("張亮");
????book3.setPrice(99f);
????book3.setBookPublicationDate(new?Date());
????bookList.add(book1);
????bookList.add(book2);
????bookList.add(book3);
????return?bookList;
}
運(yùn)行之后,直接地址欄中訪問(wèn) http://localhost:8080/getBooks,即可看到 getBooks() 方法創(chuàng)建多個(gè) Book 對(duì)象封裝在 List 集合中并將 JSON 數(shù)據(jù)返回到客戶(hù)端。

4. 更換轉(zhuǎn)換器
1)使用 Gson
Gson 是 Google 的開(kāi)源 JSON 解析器,添加依賴(lài)的時(shí)候先要去除默認(rèn)的 jackson,具體如下:
<dependency>
????<groupId>org.springframework.bootgroupId>
????<artifactId>spring-boot-starter-webartifactId>
????<exclusions>
????????<exclusion>
????????????<groupId>com.fasterxml.jackson.coregroupId>
????????????<artifactId>jackson-databindartifactId>
????????exclusion>
????exclusions>
dependency>
<dependency>
????<groupId>com.google.code.gsongroupId>
????<artifactId>gsonartifactId>
dependency>
在 Gson 轉(zhuǎn)換時(shí),如果需要格式化日期數(shù)據(jù),則需要自定義 HttpMessageConverter,接著提供一個(gè) GsonHttpMessageConverter 即可,具體如下:
@Configuration
public?class?GsonConfig?{
????@Bean
????GsonHttpMessageConverter?gsonHttpMessageConverter()?{
????????GsonHttpMessageConverter?converter?=?new?GsonHttpMessageConverter();
????????GsonBuilder?builder?=?new?GsonBuilder();
????????builder.setDateFormat("yyyy-MM-dd");
????????builder.excludeFieldsWithModifiers(Modifier.PROTECTED);
????????Gson?gson?=?builder.create();
????????converter.setGson(gson);
????????return?converter;
????}
}
修改 Book 類(lèi),具體如下:
public?class?Book?{
????private?Integer?id;
????private?String?name;
????private?String?author;
????protected?Float?price;
????private?Date?bookPublicationDate;
????//?getter?和?setter?方法
}
運(yùn)行之后,直接地址欄中訪問(wèn) http://localhost:8080/getBooks,效果如圖:

2)使用 fastjson
fastjson 是阿里巴巴的開(kāi)源 JSON 解析器,也是目前速度最快的 JSON 解析器,整合之后需要提供相應(yīng)的 HttpMessageConverter 才能使用,添加依賴(lài),具體如下:
<dependency>
????<groupId>org.springframework.bootgroupId>
????<artifactId>spring-boot-starter-webartifactId>
????<exclusions>
????????<exclusion>
????????????<groupId>com.fasterxml.jackson.coregroupId>
????????????<artifactId>jackson-databindartifactId>
????????exclusion>
????exclusions>
dependency>
<dependency>
????<groupId>com.alibabagroupId>
????<artifactId>fastjsonartifactId>
dependency>
接著,添加 fastjson 的 HttpMessageConverter,具體如下:
@Configuration
public?class?NXFastJsonConfig?{
????@Bean
????FastJsonHttpMessageConverter?fastJsonHttpMessageConverter()?{
????????FastJsonHttpMessageConverter?converter?=?new?FastJsonHttpMessageConverter();
????????FastJsonConfig?config?=?new?FastJsonConfig();
????????config.setDateFormat("yyyy-MM-dd");
????????config.setCharset(Charset.forName("UTF-8"));
????????config.setSerializerFeatures(
????????????????SerializerFeature.WriteClassName,
????????????????SerializerFeature.WriteMapNullValue,
????????????????SerializerFeature.PrettyFormat,
????????????????SerializerFeature.WriteNullListAsEmpty,
????????????????SerializerFeature.WriteNullStringAsEmpty
????????);
????????converter.setFastJsonConfig(config);
????????return?converter;
????}
}
再來(lái) application.properties 中配置一個(gè)響應(yīng)編碼,具體如下:
spring.http.encoding.force-response=true
運(yùn)行之后,直接地址欄中訪問(wèn) http://localhost:8080/getBooks,效果如圖:


公眾號(hào):江帥帥(ID:NXJSS666)
CSDN 博客:江帥帥
