JAXB 深入顯出 - JAXB 教程 Spring Boot返回JSON
摘要: JAXB 作為JDK的一部分,能便捷地將Java物件與XML進行相互轉換,本教程從實際案例出發來講解JAXB 2 的那些事兒。完整版目錄
前情回顧
前面的章節,已經把JAXB的各種使用細節講清楚了。但是真正掌握,還需要深入到專案中體驗一下。
這一節開始,將開始專注於JAXB 在 Spring專案中的使用情況,為了能快速構建Spring專案,我使用了Spring Boot 來搭建工程。
新增依賴
我使用了最基本的spring-boot-starter-web
,也就是說,專案中除了parent+web-starter沒有其他多於依賴。
完整的pom.xml檔案如下。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.training</ groupId>
<artifactId>jaxb</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>jaxb-example</name>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId >
<version>2.0.4.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
邏輯程式碼編寫
建立啟動類
在專案的最上層包中建立Spring boot的啟動類:
package com.example.demo;
@SpringBootApplication
public class WebApplication {
public static void main(String[] args) {
SpringApplication.run(WebApplication.class, args);
}
}
如果本身建立的就是SpringBoot專案,這一步是不需要的。注意該類所在的包需要在工程最頂層。
建立實體類
首先需要一個實體類,這裡模擬一個學生管理系統。建立Java bean Student
package com.example.demo.lesson20.entity;
public class Student {
private String id;
private String name;
private Integer age;
// ignore setters,getters,toString()
}
學生類有三個欄位,為了節省篇幅,我省略了setter,getter方法。
建立服務層
服務層是所有的邏輯程式碼,我沒有建立資料訪問層,模擬的資料存放在Map 集合中。使用了靜態程式碼塊來初始化資料,預設Map的key就是實體類的id,方便查詢操作。
package com.example.demo.lesson20.service;
@Service
public class StudentService {
static Map<String, Student> students = new HashMap<>();
static {
students.put("11", new Student("11", "Tom", 23));
students.put("12", new Student("12", "Jerry", 25));
students.put("13", new Student("13", "David", 32));
students.put("14", new Student("14", "Jack", 41));
}
public Student findById(String id) {
return students.get(id);
}
}
這裡的方法 findById()
是需要我們通過id查詢對應的學生資訊,這在真實專案中非常常見。需要注意返回值是對應的Java bean。
Rest介面
SpringBoot推薦我們通過暴露Http介面的方式供外部訪問,我使用@RestController
來標註 Controller 層,而這裡的@RestController
並沒有什麼特殊的,它只是包裝了之前常見的兩個註解:@Controller
,@ResponseBody
。
package com.example.demo.lesson20.web;
@RestController
@RequestMapping("/student")
public class StudentController {
@Autowired
private StudentService studentService;
@GetMapping(value="/id")
public Student findById(String id) {
return studentService.findById(id);
}
}
我的第一個方法很簡單,對映的路徑格式為 contextPath/student/id?id=xx
,需要注意返回值型別為Student
。
測試資料
看到控制檯輸出Started WebApplication in 5.816 seconds (JVM running for 7.372)
,專案已經啟動成功。
在瀏覽器中訪問: http://localhost:8080/student/id?id=11
可以正確的返回Json格式的資料。
為什麼返回的是JSON格式,通過瀏覽器的除錯視窗檢視一下,返回的Content-Type
為’application/json;charset=UTF-8’。原來,Spring在處理返回資料的時候,已經為請求加上返回型別。
豐富服務層
在之前的基礎上,還有一個需求,返回所有學生資訊。因此在之前的Service層程式碼上新增如下程式碼:
StudentService.java
public List<Student> findAll() {
return new ArrayList<Student>(students.values());
}
這裡把Map中所有的 values 資料轉換為了ArrayList<Student>
型別,返回資料型別為List<Student>
。
豐富控制層
StudentController.java
@GetMapping(value="/list")
public List<Student> findAll(){
return studentService.findAll();
}
和之前的查詢單個數據一樣,返回多個數據看起來更簡單,不過需要注意,返回資料型別為List<Student>
。
測試資料
重啟專案,看到控制檯輸出Started WebApplication in 5.816 seconds (JVM running for 7.372)
,專案已經啟動成功。
在瀏覽器中訪問: http://localhost:8080/student/list
可以正確的返回Json格式的資料。
完整程式碼
可以在GitHub找到完整程式碼。
本節程式碼均在該包下:package com.example.demo.lesson20;
下節預覽
這一節主要是搭建SpringBoot專案的骨架,演示瞭如何快速實現一套restful介面,返回的資料型別是JSON。看起來沒有什麼特殊處理,Spring對JSON資料友好地支援了。
下一節將從這兩個例子出發,看一下返回XML資料需要如何處理。