欢迎访问我的GitHub

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如下:
<?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 https://maven.apache.org/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>springbootconfigbean</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springbootconfigbean</name>
<description>Demo project for Spring Boot with Jackson, configuration from config bean</description> <properties>
<java.version>1.8</java.version>
</properties> <!--不用spring-boot-starter-parent作为parent时的配置-->
<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>
  1. 本文最重要的代码是配置类JacksonConfig.java,如下,需要ConditionalOnMissingBean注解避免冲突,另外还给实例指定了名称customizeObjectMapper,如果应用中通过Autowired使用此实例,需要指定这个名字,避免报错"There is more than one bean of 'ObjectMapper ' type":
@Configuration
public class JacksonConfig { @Bean("customizeObjectMapper")
@Primary
@ConditionalOnMissingBean(ObjectMapper.class)
public ObjectMapper getObjectMapper(Jackson2ObjectMapperBuilder builder) {
ObjectMapper mapper = builder.build(); // 日期格式
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")); // 美化输出
mapper.enable(SerializationFeature.INDENT_OUTPUT); return mapper;
}
}
  1. 对于JacksonConfig.getObjectMapper方法内的设置,如果您想做更多设置,请参考《jackson学习之三:常用API操作》里面的设置内容;
  • 启动类依然很简单:
package com.bolingcavalry.springbootconfigbean;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication
public class SpringbootConfigBeanApplication { public static void main(String[] args) {
SpringApplication.run(SpringbootConfigBeanApplication.class, args);
} }
  1. swagger配置:
package com.bolingcavalry.springbootconfigbean;

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相关测试"))
.select()
// 当前包路径
.apis(RequestHandlerSelectors.basePackage("com.bolingcavalry.springbootconfigbean.controller"))
.paths(PathSelectors.any())
.build();
} //构建 api文档的详细信息函数,注意这里的注解引用的是哪个
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
//页面标题
.title("SpringBoot整合Jackson(基于配置文件)")
//创建人
.contact(new Contact("程序员欣宸", "https://github.com/zq2599/blog_demos", "zq2599@gmail.com"))
//版本号
.version("1.0")
//描述
.description("API 描述")
.build();
}
}
  1. 最后是测试用的Controller类,要注意的是在使用ObjectMapper实例的地方,用Autowired注解的时候,记得带上Qualifier注解:
package com.bolingcavalry.springbootconfigbean.controller;

import com.bolingcavalry.springbootconfigbean.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.beans.factory.annotation.Qualifier;
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); @Qualifier("customizeObjectMapper")
@Autowired
ObjectMapper mapper; @ApiOperation(value = "测试序列化", notes = "测试序列化")
@RequestMapping(value = "/serialization", method = RequestMethod.GET)
public Test serialization() throws JsonProcessingException { Test test = new Test();
logger.info(mapper.writeValueAsString(test)); return test;
} @ApiOperation(value = "测试反序列化", notes="测试反序列化")
@RequestMapping(value = "/deserialization",method = RequestMethod.PUT)
public String deserialization(@RequestBody Test test) {
return test.toString();
}
}

验证

  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

jackson学习之十(终篇):springboot整合(配置类)的更多相关文章

  1. 从.Net到Java学习第十二篇——SpringBoot+JPA提供跨域接口

    从.Net到Java学习系列目录 最近又撸了半个月的前端代码,做app离线存储,然后又花了一周去将过去的wcf项目转webapi,java又被落下了,总感觉我特么像斗地主中的癞子牌,变来变去..... ...

  2. springboot(十四):springboot整合shiro-登录认证和权限管理(转)

    springboot(十四):springboot整合shiro-登录认证和权限管理 .embody{ padding:10px 10px 10px; margin:0 -20px; border-b ...

  3. SpringBoot系列十二:SpringBoot整合 Shiro

    声明:本文来源于MLDN培训视频的课堂笔记,写在这里只是为了方便查阅. 1.概念:SpringBoot 整合 Shiro 2.具体内容 Shiro 是现在最为流行的权限认证开发框架,与它起名的只有最初 ...

  4. 第三篇 SpringBoot整合log4j2详解

    源代码:https://pan.baidu.com/s/1d1Lwv1gIvVNltIKVWeEseA 提取码:wff0 SpringBoot整合Log4j2步骤: 1.删除spring-boot-s ...

  5. rabbitmq学习(五):springboot整合rabbitmq

    一.Springboot对rabbitmq的支持 springboot提供了对rabbitmq的支持,并且大大简化了rabbitmq的相关配置.在springboot中,框架帮我们将不同的交换机划分出 ...

  6. Redis和springboot 整合redisUtil类

    一.引入依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId> ...

  7. Redis和SpringBoot整合RedisUtils类

    一.引入依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId> ...

  8. springboot项目配置类

    一.在springboot项目中,如果不进行配置,直接访问静态页面是无法访问的,需要进行配置,springboot舍弃了XML文件的配置方式,这里我们采用开发配置类的方式.新建MvcConfig类,加 ...

  9. SpringBoot第十二篇:整合jsp

    作者:追梦1819 原文:https://www.cnblogs.com/yanfei1819/p/10953600.html 版权声明:本文为博主原创文章,转载请附上博文链接! 引言   Sprin ...

随机推荐

  1. show slave status常用参数备忘

    mysql> show slave status\G*************************** 1. row *************************** Slave_IO ...

  2. kubernets之服务重定向

    一  服务的强大功能之处的其他表现 前面介绍的所有有关服务的说明,都是将集群内部的pod应用暴露出来提供外部客户端或者内部的客户端进行访问,但是服务的强大之处远远不止于此 服务甚至可以将集群外部的应用 ...

  3. 敏感信息泄露 - Pikachu

    概述: 由于后台人员的疏忽或者不当的设计,导致不应该被前端用户看到的数据被轻易的访问到. 比如:---通过访问url下的目录,可以直接列出目录下的文件列表;---输入错误的url参数后报错信息里面包含 ...

  4. AQS之ReentrantReadWriteLock精讲分析上篇

    1.用法 1.1 定义一个安全的list集合 public class LockDemo { ArrayList<Integer> arrayList = new ArrayList< ...

  5. Java中,那些关于String和字符串常量池你不得不知道的东西

    老套的笔试题 在一些老套的笔试题中,会要你判断s1==s2为false还是true,s1.equals(s2)为false还是true. String s1 = new String("xy ...

  6. CMU数据库(15-445)实验2-b+树索引实现(上)

    Lab2 在做实验2之前请确保实验1结果的正确性.不然你的实验2将无法正常进行 环境搭建地址如下 https://www.cnblogs.com/JayL-zxl/p/14307260.html 实验 ...

  7. SpringIOC的注解应用

    SpringIOC的注解应用 ​ 在之前的项目中,我们都是通过xml文件进行bean或者某些属性的赋值,其实还有另外一种注解的方式,在企业开发中使用的很多,在bean上添加注解,可以快速的将bean注 ...

  8. java画海报二维码

    package cn.com.yitong.ares.qrcode; import java.awt.BasicStroke;import java.awt.Color;import java.awt ...

  9. 慕课网金职位 Java工程师2020 百度网盘下载

    百度网盘链接:https://pan.baidu.com/s/1xshLRO3ru0LAsQQ0pE67Qg 提取码:bh9f 如果失效加我微信:610060008[视频不加密,资料代码齐全,超清一手 ...

  10. 常用shell命令及其用法

    ls(lsit) ​ 1.作用:列出文件列表 ​ 2.用法:ls [-a|-A--] [filename|directory] ​ ls ​ ls -a:查看隐藏文件 ​ ls -l:查看文件详细信息 ...