1、返回 JSON 数据 1.1、默认实现 1.2、自定义转换器
1.2.1 使用 Gson
1.2.2 使用 fastjson
1、返回 JSON 数据
1.1、默认实现
JSON 是主流的前后端数据传输方式,Spring MVC使用消息转换器 HttpMessageConverter 对 JSON 的转换提供很好的支持,在 Spring Boot 中更进一步,对相关配置做了更进一步的简化,创建一个 Spring Boot 项目后,添加 Web 依赖,代码如下:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
这个依赖中默认加入了 jackson-databind 作为 JSON 处理器,此时不需要添加额外的 JSON 处 理器就能返回一段 JSON了。 创建一个 Book 实体类:
package com.zrq.Bean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import java.util.Date;
//@Component
@PropertySource(value = "classpath:books.properties")
//@ConfigurationProperties(prefix = "book")
public class Book {
private String name;
private String author;
protected Float price;
private Date publicationDate;
//省略getter/setter
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Float getPrice() {
return price;
}
public void setPrice(Float price) {
this.price = price;
}
public Date getPublicationDate() {
return publicationDate;
}
public void setPublicationDate(Date publicationDate) {
this.publicationDate = publicationDate;
}
}
然后创建 BookController, 返回 Book 对象即可:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
@RestController
public class BookController {
@GetMapping("/book")
public Book book() {
Book book = new Book();
book.setAuthor("zhangruiqin");
book.setName("基于Hadoop的文本聚类研究");
book.setPrice(100f);
book.setPublicationDate(new Date());
return book;
}
@GetMapping("/hello")
public String hello() {
return "hello zrq";
}
}
此时, 在浏览器中输入 https://localhost:8081/spring-vue/book
这是 Spring Boot 自带的处理方式。如果采用这种方式,那么对于字段忽略、日期格式化等常 见需求都可以通过注解来解决。
1.2、自定义转换器
常见的 JSON 处理器除了 jackson-databind 之外, 还有 Gson 和 fastjson, 这里针对常见用法分 别举例。
1.2.1 使用 Gson
Gson 是 Google 的一个开源 JSON 解析框架。使用 Gson,需要先除去默认的jackson-datab1时, 然后加入 Gson 依赖,代码如下:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<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>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
Spring Boot 中默认提供了Gson 自动转换类GsonHttpMessageConvertersConfiguration, 因此 Gson 的依赖添加成功后, 可以像使用 jackson-databind 那样直接使用 Gson。但是在 Gson 进行转换时,想对日期数据进行格式化,需要开发者自定义 HttpMessageConverter。自定义HttpMessageConverter需要提供一个 GsonHttpMessageConverter
public class GsonConfig {
@Bean
GsonHttpMessageConverter gsonHttpMessageConverter() {
GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
//开发者自己提供一个 Gson即MessageConverter 的实例
GsonBuilder builder = new GsonBuilder();
builder.setDateFormat("yyyy-MM-dd");//设置 Gson 解析时日期的格式
builder.excludeFieldsWithModifiers(Modifier.PROTECTED);
//设置 Gson 解析时修饰符为 protected 的字段被过滤掉。
Gson gson = builder.create();//创建 Gson对象放入GsonHttpMessageConverter的实例中
//并返回 converter
converter.setGson(gson);
return converter;
}
}
运行结果:
1.2.2 使用 fastjson
fastjson 是阿里巴巴的一个开源 JSON 解析框架, 是目前 JSON 解析速度最快的开源框架,该框架也可以集成到 Spring Boot 中。 fastjson 继承完成之后并不能立马使用, 需要开 发者提供相应的 HttpMessageConverter 后才能使用,集成 fastjson 的步骤如下:
首先除去 jackson-databind 依赖,引入 fastjson 依赖:
<dependency>
<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>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
然后配置 fastjson 的 HttpMessageConverter:
自定义MyFastJsonConfig,完成对FastJsonHttpMessageConverter的提供。
import java.nio.charset.Charset;
//@Configuration
public class MyFastJsonConfig {
// @Bean
FastJsonHttpMessageConverter fastJsonHttpMessageConverter() {
FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
FastJsonConfig config = new FastJsonConfig();
/**
*
* 配直了 JSON 解析过程的一些细节,例如日期格式、数据编码、是否在生成的 JSON 中输出类名
* 、是否输出 value 为 null 的数据、生成的 JSON 格式化、空集合输出口而非 null、空字符
* 串输出’”’而非 null 等基本配直。
*/
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;
}
}
MyFastJsonConfig 配置完成后,还需要配置一下响应编码,否则返回的 JSON 中文会乱码,在application. properties 中添加如下配置:
spring.http.encoding.force-response=true
提供 BookController 进行测试。 BookController 和上一小节一致,运行结果