歡迎訪問(wèn)我的GitHub
這里分類和匯總了欣宸的全部原創(chuàng)(含配套源碼):https://github.com/zq2599/blog_demos
系列文章匯總
關(guān)于springboot整合jackson
- 本文是《jackson學(xué)習(xí)》系列的第九篇,學(xué)習(xí)如何在springboot項(xiàng)目中使用jackson,以springboot-2.3.3版本為例,jackson是springboot的默認(rèn)json處理工具,如下圖紅框所示,jackson在maven配置中被spring-boot-starter-web間接依賴,可直接使用:

- 在springboot項(xiàng)目中常用的配置方式有兩種:
- 用properties或yml配置文件來(lái)配置,即本篇的內(nèi)容;
- 用配置類來(lái)配置,這是下一篇文章的主題;
本篇概覽
今天實(shí)戰(zhàn)內(nèi)容如下:
- 開發(fā)springboot應(yīng)用,體驗(yàn)springboot默認(rèn)支持jackson,包括jackson注解和ObjectMapper實(shí)例的注入;
- 在application.yml中添加jackson配置,驗(yàn)證是否生效;
源碼下載
- 如果您不想編碼,可以在GitHub下載所有源碼,地址和鏈接信息如下表所示(https://github.com/zq2599/blog_demos):
- 這個(gè)git項(xiàng)目中有多個(gè)文件夾,本章的應(yīng)用在jacksondemo文件夾下,如下圖紅框所示:

- jacksondemo是父子結(jié)構(gòu)的工程,本篇的代碼在springbootproperties子工程中,如下圖:

開始實(shí)戰(zhàn)
- 由于同屬于《jackson學(xué)習(xí)》系列文章,因此本篇的springboot工程作為jacksondemo的子工程存在,pom.xml如下,需要注意的是parent不能使用spring-boot-starter-parent,而是通過(guò)dependencyManagement節(jié)點(diǎn)來(lái)引入springboot依賴:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven./POM/4.0.0" xmlns:xsi="http://www./2001/XMLSchema-instance"
xsi:schemaLocation="http://maven./POM/4.0.0 https://maven./xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>jacksondemo</artifactId>
<groupId>com.bolingcavalry</groupId>
<version>1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<groupId>com.bolingcavalry</groupId>
<artifactId>springbootproperties</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springbootproperties</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<!--不用spring-boot-starter-parent作為parent時(shí)的配置-->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.3.3.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- swagger依賴 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<!-- swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
- 啟動(dòng)類很平常:
package com.bolingcavalry.springbootproperties;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringbootpropertiesApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootpropertiesApplication.class, args);
}
}
- 由于用到了swagger,因此要添加swagger配置:
package com.bolingcavalry.springbootproperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Tag;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.tags(new Tag("JsonPropertySerializationController", "JsonProperty相關(guān)測(cè)試"))
.select()
// 當(dāng)前包路徑
.apis(RequestHandlerSelectors.basePackage("com.bolingcavalry.springbootproperties.controller"))
.paths(PathSelectors.any())
.build();
}
//構(gòu)建 api文檔的詳細(xì)信息函數(shù),注意這里的注解引用的是哪個(gè)
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
//頁(yè)面標(biāo)題
.title("SpringBoot整合Jackson(基于配置文件)")
//創(chuàng)建人
.contact(new Contact("程序員欣宸", "https://github.com/zq2599/blog_demos", "zq2599@gmail.com"))
//版本號(hào)
.version("1.0")
//描述
.description("API 描述")
.build();
}
}
- 序列化和反序列化用到的Bean類,可見(jiàn)使用了JsonProperty屬性來(lái)設(shè)置序列化和反序列化時(shí)的json屬性名,field0字段刻意沒(méi)有g(shù)et方法,是為了驗(yàn)證JsonProperty的序列化能力:
package com.bolingcavalry.springbootproperties.bean;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.Date;
@ApiModel(description = "JsonProperty注解測(cè)試類")
public class Test {
@ApiModelProperty(value = "私有成員變量")
@JsonProperty(value = "json_field0", index = 1)
private Date field0 = new Date();
public void setField0(Date field0) {
this.field0 = field0;
}
@ApiModelProperty(value = "來(lái)自get方法的字符串")
@JsonProperty(value = "json_field1", index = 0)
public String getField1() {
return "111";
}
@Override
public String toString() {
return "Test{" +
"field0=" + field0 +
'}';
}
}
- 測(cè)試用的Controller代碼如下,很簡(jiǎn)單只有兩個(gè)接口,serialization返回序列化結(jié)果,deserialization接受客戶端請(qǐng)求參數(shù),反序列化成實(shí)例,通過(guò)toString()來(lái)檢查反序列化的結(jié)果,另外,還通過(guò)Autowired注解從spring容器中將ObjectMapper實(shí)例直接拿來(lái)用:
package com.bolingcavalry.springbootproperties.controller;
import com.bolingcavalry.springbootproperties.bean.Test;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/jsonproperty")
@Api(tags = {"JsonPropertySerializationController"})
public class JsonPropertySerializationController {
private static final Logger logger = LoggerFactory.getLogger(JsonPropertySerializationController.class);
@Autowired
ObjectMapper mapper;
@ApiOperation(value = "測(cè)試序列化", notes = "測(cè)試序列化")
@RequestMapping(value = "/serialization", method = RequestMethod.GET)
public Test serialization() throws JsonProcessingException {
Test test = new Test();
logger.info(mapper.writeValueAsString(test));
return test;
}
@ApiOperation(value = "測(cè)試反序列化", notes="測(cè)試反序列化")
@RequestMapping(value = "/deserialization",method = RequestMethod.PUT)
public String deserialization(@RequestBody Test test) {
return test.toString();
}
}
驗(yàn)證(不用配置文件)
- 先來(lái)看看沒(méi)有配置文件時(shí),默認(rèn)的jackson配置的表現(xiàn),直接在IDEA上運(yùn)行SpringbootpropertiesApplication;
- 瀏覽器訪問(wèn)http://localhost:8080/swagger-ui.html ,如下圖紅框1,json_field0和json_field1都是JsonProperty注釋,出現(xiàn)在了swagger的model中,這證明jackson注解已經(jīng)生效:

- 點(diǎn)擊上圖的紅框2,看看springboot引用返回的序列化結(jié)果,如下圖:

- 另外,上述紅框中的json格式,每個(gè)屬性單獨(dú)一行,像是做了格式化調(diào)整的,這是springboot做的?還是swagger展示的時(shí)候做的?用瀏覽器訪問(wèn)http://localhost:8080/jsonproperty/serialization ,結(jié)果如下,可見(jiàn)springboot返回的是未經(jīng)過(guò)格式化的json:

- 接下來(lái)咱們添加jackson相關(guān)的配置信息并驗(yàn)證是否生效;
添加配置文件并驗(yàn)證
- 在resources目錄新增application.yml文件,內(nèi)容如下:
spring:
jackson:
# 日期格式化
date-format: yyyy-MM-dd HH:mm:ss
# 序列化相關(guān)
serialization:
# 格式化輸出
indent_output: true
# 忽略無(wú)法轉(zhuǎn)換的對(duì)象
fail_on_empty_beans: true
# 反序列化相關(guān)
deserialization:
# 解析json時(shí),遇到不存在的屬性就忽略
fail_on_unknown_properties: false
# 設(shè)置空如何序列化
defaultPropertyInclusion: NON_EMPTY
parser:
# 允許特殊和轉(zhuǎn)義符
allow_unquoted_control_chars: true
# 允許單引號(hào)
allow_single_quotes: true
- 將鼠標(biāo)放置下圖紅框位置,再按住Ctlr鍵,IDEA會(huì)彈出一個(gè)浮層,提示該配置對(duì)應(yīng)的jackson代碼,如下圖:

- 在上圖中,按住Ctlr鍵,用鼠標(biāo)點(diǎn)擊紅框位置即可打開此配置對(duì)應(yīng)的jackson源碼,如下圖:

4. 重新運(yùn)行springboot應(yīng)用,用瀏覽器訪問(wèn):http://localhost:8080/jsonproperty/serialization ,結(jié)果如下圖,可見(jiàn)json_field0的格式變成了yyyy-MM-dd HH:mm:ss,而且json輸出也做了格式化,證明application.yml中的配置已經(jīng)生效:

5. 再來(lái)試試反序列化,打開swagger頁(yè)面,操作和響應(yīng)如下圖所示,注意紅框1里面請(qǐng)求參數(shù)的格式:

- 至此,在springboot中通過(guò)yml配置jackson的操作實(shí)戰(zhàn)就完成了,接下來(lái)的章節(jié),咱們?cè)谂渲妙愔杏么a來(lái)完成yml的配置;
你不孤單,欣宸原創(chuàng)一路相伴
- Java系列
- Spring系列
- Docker系列
- kubernetes系列
- 數(shù)據(jù)庫(kù)+中間件系列
- DevOps系列
歡迎關(guān)注公眾號(hào):程序員欣宸
微信搜索「程序員欣宸」,我是欣宸,期待與您一同暢游Java世界...
https://github.com/zq2599/blog_demos
|