JAXB 深入显出 - JAXB 教程 Spring Boot返回JSON

x33g5p2x  于2021-12-28 转载在 其他  
字(4.3k)|赞(0)|评价(0)|浏览(296)

摘要: 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数据需要如何处理。

相关文章