開發與維運

江帥帥:精通 Spring Boot 系列 05

Spring Boot 處理 JSON 數據
JSON 是目前主流的前後端數據傳輸方式,當 Controller 中返回的是一個 Java 對象或 List 集合時,Spring Boot 將自動把它轉換成 JSON 數據。

Spring Boot 中內置了 JSON 解析功能,當你在項目中,添加了 spring-boot-starter-web 模塊之後,即可看到默認包含 Jackson 解析器,也可以換成 Fastjson 等其他解析器。

  1. 編輯 Book 類
  2. 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 方法

}

  1. 編輯 BookController
    返回數據的時候,需要使用 @ResponseBody 註解。如果經常使用 @Controller 和 @ResponseBody 註解,則可以使用 @RestController 組合註解來替代。

@RestController
public class BookController {

@GetMapping("/book")
public Book book(){
    Book book = new Book();
    book.setId(1);
    book.setName("《碼農翻身:用故事給技術加點料》");
    book.setAuthor("劉欣");
    book.setPrice(69f);
    book.setBookPublicationDate(new Date());

    return book;
}

}
運行之後,直接地址欄中訪問 http://localhost:8080/book,即可看到返回的 JSON 數據。

1.jpg

  1. 轉換集合數據
    添加 getBooks() 方法,創建一個 List 集合,存放三本書。具體源碼如下:

@RequestMapping("/getBooks")
public List getBooks() {

List<Book> bookList = new ArrayList<>();

Book book1 = new Book();
book1.setId(1);
book1.setName("《碼農翻身:用故事給技術加點料》");
book1.setAuthor("劉欣");
book1.setPrice(69f);
book1.setBookPublicationDate(new Date());

Book book2 = new Book();
book2.setId(2);
book2.setName("《漫畫算法:小灰的算法之旅(全綵)》");
book2.setAuthor("魏夢舒");
book2.setPrice(79f);
book2.setBookPublicationDate(new Date());

Book book3 = new Book();
book3.setId(3);
book3.setName("《未來架構》");
book3.setAuthor("張亮");
book3.setPrice(99f);
book3.setBookPublicationDate(new Date());

bookList.add(book1);
bookList.add(book2);
bookList.add(book3);

return bookList;

}
運行之後,直接地址欄中訪問 http://localhost:8080/getBooks,即可看到 getBooks() 方法創建多個 Book 對象封裝在 List 集合中並將 JSON 數據返回到客戶端。

2.jpg

  1. 更換轉換器
    1)使用 Gson

Gson 是 Google 的開源 JSON 解析器,添加依賴的時候先要去除默認的 jackson,具體如下:

<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
    <exclusion>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
    </exclusion>
</exclusions>

<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>

在 Gson 轉換時,如果需要格式化日期數據,則需要自定義 HttpMessageConverter,接著提供一個 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 類,具體如下:

public class Book {

private Integer id;
private String name;
private String author;
protected Float price;
private Date bookPublicationDate;

// getter 和 setter 方法

}
運行之後,直接地址欄中訪問 http://localhost:8080/getBooks,效果如圖:

3.jpg

2)使用 fastjson
fastjson 是阿里巴巴的開源 JSON 解析器,也是目前速度最快的 JSON 解析器,整合之後需要提供相應的 HttpMessageConverter 才能使用,添加依賴,具體如下:

<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
    <exclusion>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
    </exclusion>
</exclusions>

<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>

接著,添加 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;
}

}
再來 application.properties 中配置一個響應編碼,具體如下:

spring.http.encoding.force-response=true
運行之後,直接地址欄中訪問 http://localhost:8080/getBooks,效果如圖:

4.jpg
本文來源於:奈學開發者社區-江帥帥

Leave a Reply

Your email address will not be published. Required fields are marked *