天天看點

江帥帥:精通 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 資料。

江帥帥:精通 Spring Boot 系列 05
  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 資料傳回到用戶端。

江帥帥:精通 Spring Boot 系列 05
  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 方法           

,效果如圖:

江帥帥:精通 Spring Boot 系列 05

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,具體如下:

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

江帥帥:精通 Spring Boot 系列 05

本文來源于:奈學開發者社群-江帥帥