https://github.com/zq2599/blog_demos

内容:所有原创文章分类汇总及配套源码,涉及Java、Docker、Kubernetes、DevOPS等;

  • 本文是《jackson学习》系列的终篇,经过前面的一系列实战,相信您已可以熟练使用jackson灵活的执行各种json序列化和反序列化操作,那么,本篇就以轻松的方式来完成整个系列吧;
  • 上一篇介绍的是在springboot中通过配置文件对jackson做设置,今天要聊的是另一种常用的jackson配置方式:配置类,就是自己编写代码实例化和配置springboot全局使用的ObjectMapper实例;
  1. 如果您不想编码,可以在GitHub下载所有源码,地址和链接信息如下表所示(https://github.com/zq2599/blog_demos):
名称 链接 备注
项目主页 https://github.com/zq2599/blog_demos 该项目在GitHub上的主页
git仓库地址(https) https://github.com/zq2599/blog_demos.git 该项目源码的仓库地址,https协议
git仓库地址(ssh) git@github.com:zq2599/blog_demos.git 该项目源码的仓库地址,ssh协议
  1. 这个git项目中有多个文件夹,本章的应用在jacksondemo文件夹下,如下图红框所示:

在这里插入图片描述

  1. jacksondemo是父子结构的工程,本篇的代码在springbootconfigbean子工程中,如下图:

在这里插入图片描述

  1. 在父工程jacksondemo下新增子工程springbootconfigbean,pom.xml如下:
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <artifactId>jacksondemo</artifactId>
  7. <groupId>com.bolingcavalry</groupId>
  8. <version>1.0-SNAPSHOT</version>
  9. <relativePath>../pom.xml</relativePath>
  10. </parent>
  11. <groupId>com.bolingcavalry</groupId>
  12. <artifactId>springbootconfigbean</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>springbootconfigbean</name>
  15. <description>Demo project for Spring Boot with Jackson, configuration from config bean</description>
  16. <properties>
  17. <java.version>1.8</java.version>
  18. </properties>
  19. <!--不用spring-boot-starter-parent作为parent时的配置-->
  20. <dependencyManagement>
  21. <dependencies>
  22. <dependency>
  23. <groupId>org.springframework.boot</groupId>
  24. <artifactId>spring-boot-dependencies</artifactId>
  25. <version>2.3.3.RELEASE</version>
  26. <type>pom</type>
  27. <scope>import</scope>
  28. </dependency>
  29. </dependencies>
  30. </dependencyManagement>
  31. <dependencies>
  32. <dependency>
  33. <groupId>org.springframework.boot</groupId>
  34. <artifactId>spring-boot-starter-web</artifactId>
  35. </dependency>
  36. <dependency>
  37. <groupId>org.springframework.boot</groupId>
  38. <artifactId>spring-boot-starter-test</artifactId>
  39. <scope>test</scope>
  40. <exclusions>
  41. <exclusion>
  42. <groupId>org.junit.vintage</groupId>
  43. <artifactId>junit-vintage-engine</artifactId>
  44. </exclusion>
  45. </exclusions>
  46. </dependency>
  47. <!-- swagger依赖 -->
  48. <dependency>
  49. <groupId>io.springfox</groupId>
  50. <artifactId>springfox-swagger2</artifactId>
  51. </dependency>
  52. <!-- swagger-ui -->
  53. <dependency>
  54. <groupId>io.springfox</groupId>
  55. <artifactId>springfox-swagger-ui</artifactId>
  56. </dependency>
  57. </dependencies>
  58. <build>
  59. <plugins>
  60. <plugin>
  61. <groupId>org.springframework.boot</groupId>
  62. <artifactId>spring-boot-maven-plugin</artifactId>
  63. </plugin>
  64. </plugins>
  65. </build>
  66. </project>
  1. 本文最重要的代码是配置类JacksonConfig.java,如下,需要ConditionalOnMissingBean注解避免冲突,另外还给实例指定了名称customizeObjectMapper,如果应用中通过Autowired使用此实例,需要指定这个名字,避免报错”There is more than one bean of ‘ObjectMapper ‘ type”:
  1. @Configuration
  2. public class JacksonConfig {
  3. @Bean("customizeObjectMapper")
  4. @Primary
  5. @ConditionalOnMissingBean(ObjectMapper.class)
  6. public ObjectMapper getObjectMapper(Jackson2ObjectMapperBuilder builder) {
  7. ObjectMapper mapper = builder.build();
  8. // 日期格式
  9. mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"));
  10. // 美化输出
  11. mapper.enable(SerializationFeature.INDENT_OUTPUT);
  12. return mapper;
  13. }
  14. }
  1. 对于JacksonConfig.getObjectMapper方法内的设置,如果您想做更多设置,请参考《jackson学习之三:常用API操作》里面的设置内容;
  • 启动类依然很简单:
  1. package com.bolingcavalry.springbootconfigbean;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. @SpringBootApplication
  5. public class SpringbootConfigBeanApplication {
  6. public static void main(String[] args) {
  7. SpringApplication.run(SpringbootConfigBeanApplication.class, args);
  8. }
  9. }
  1. swagger配置:
  1. package com.bolingcavalry.springbootconfigbean;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import springfox.documentation.builders.ApiInfoBuilder;
  5. import springfox.documentation.builders.PathSelectors;
  6. import springfox.documentation.builders.RequestHandlerSelectors;
  7. import springfox.documentation.service.ApiInfo;
  8. import springfox.documentation.service.Contact;
  9. import springfox.documentation.service.Tag;
  10. import springfox.documentation.spi.DocumentationType;
  11. import springfox.documentation.spring.web.plugins.Docket;
  12. import springfox.documentation.swagger2.annotations.EnableSwagger2;
  13. @Configuration
  14. @EnableSwagger2
  15. public class SwaggerConfig {
  16. @Bean
  17. public Docket createRestApi() {
  18. return new Docket(DocumentationType.SWAGGER_2)
  19. .apiInfo(apiInfo())
  20. .tags(new Tag("JsonPropertySerializationController", "JsonProperty相关测试"))
  21. .select()
  22. // 当前包路径
  23. .apis(RequestHandlerSelectors.basePackage("com.bolingcavalry.springbootconfigbean.controller"))
  24. .paths(PathSelectors.any())
  25. .build();
  26. }
  27. //构建 api文档的详细信息函数,注意这里的注解引用的是哪个
  28. private ApiInfo apiInfo() {
  29. return new ApiInfoBuilder()
  30. //页面标题
  31. .title("SpringBoot整合Jackson(基于配置文件)")
  32. //创建人
  33. .contact(new Contact("程序员欣宸", "https://github.com/zq2599/blog_demos", "zq2599@gmail.com"))
  34. //版本号
  35. .version("1.0")
  36. //描述
  37. .description("API 描述")
  38. .build();
  39. }
  40. }
  1. 最后是测试用的Controller类,要注意的是在使用ObjectMapper实例的地方,用Autowired注解的时候,记得带上Qualifier注解
  1. package com.bolingcavalry.springbootconfigbean.controller;
  2. import com.bolingcavalry.springbootconfigbean.bean.Test;
  3. import com.fasterxml.jackson.core.JsonProcessingException;
  4. import com.fasterxml.jackson.databind.ObjectMapper;
  5. import io.swagger.annotations.Api;
  6. import io.swagger.annotations.ApiOperation;
  7. import org.slf4j.Logger;
  8. import org.slf4j.LoggerFactory;
  9. import org.springframework.beans.factory.annotation.Autowired;
  10. import org.springframework.beans.factory.annotation.Qualifier;
  11. import org.springframework.web.bind.annotation.RequestBody;
  12. import org.springframework.web.bind.annotation.RequestMapping;
  13. import org.springframework.web.bind.annotation.RequestMethod;
  14. import org.springframework.web.bind.annotation.RestController;
  15. @RestController
  16. @RequestMapping("/jsonproperty")
  17. @Api(tags = {"JsonPropertySerializationController"})
  18. public class JsonPropertySerializationController {
  19. private static final Logger logger = LoggerFactory.getLogger(JsonPropertySerializationController.class);
  20. @Qualifier("customizeObjectMapper")
  21. @Autowired
  22. ObjectMapper mapper;
  23. @ApiOperation(value = "测试序列化", notes = "测试序列化")
  24. @RequestMapping(value = "/serialization", method = RequestMethod.GET)
  25. public Test serialization() throws JsonProcessingException {
  26. Test test = new Test();
  27. logger.info(mapper.writeValueAsString(test));
  28. return test;
  29. }
  30. @ApiOperation(value = "测试反序列化", notes="测试反序列化")
  31. @RequestMapping(value = "/deserialization",method = RequestMethod.PUT)
  32. public String deserialization(@RequestBody Test test) {
  33. return test.toString();
  34. }
  35. }
  1. 启动SpringbootConfigBeanApplication后,浏览器打开:http://localhost:8080/swagger-ui.html
  2. 先验证序列化接口/jsonproperty/serialization:

在这里插入图片描述
3. 再验证反序列化接口 /jsonproperty/deserialization:

在这里插入图片描述

  • 至此,整个《jackson学习》系列就全部完成了,希望这十篇内容能够给您带来一些参考,助您在编码过程中更加得心应手的使用Jackson;
  1. Java系列
  2. Spring系列
  3. Docker系列
  4. kubernetes系列
  5. 数据库+中间件系列
  6. DevOps系列

微信搜索「程序员欣宸」,我是欣宸,期待与您一同畅游Java世界…
https://github.com/zq2599/blog_demos

版权声明:本文为bolingcavalry原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/bolingcavalry/p/14387543.html