SpringBoot 默认json解析器详解和字段序列化自定义
前言
在我们开发项目API接口的时候,一些没有数据的字段会默认返回NULL,数字类型也会是NULL,这个时候前端希望字符串能够统一返回空字符,数字默认返回0,那我们就需要自定义json序列化处理
SpringBoot默认的json解析方案
我们知道在springboot中有默认的json解析器,Spring Boot 中默认使用的 Json 解析技术框架是 jackson。我们点开 pom.xml 中的 spring-boot-starter-web 依赖,可以看到一个 spring-boot-starter-json 依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-json</artifactId>
<version>2.4.7</version>
<scope>compile</scope>
</dependency>
Spring Boot 中对依赖都做了很好的封装,可以看到很多 spring-boot-starter-xxx 系列的依赖,这是 Spring Boot 的特点之一,不需要人为去引入很多相关的依赖了,starter-xxx 系列直接都包含了所必要的依赖,所以我们再次点进去上面这个 spring-boot-starter-json 依赖,可以看到:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.4</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jdk8</artifactId>
<version>2.11.4</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.11.4</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-parameter-names</artifactId>
<version>2.11.4</version>
<scope>compile</scope>
</dependency>
我们在controller中返回json时候通过注解@ResponseBody就可以自动帮我们将服务端返回的对象序列化成json字符串,在传递json body参数时候 通过在对象参数上@RequestBody注解就可以自动帮我们将前端传过来的json字符串反序列化成java对象
这些功能都是通过HttpMessageConverter这个消息转换工具类来实现的
SpringMVC自动配置了Jackson和Gson的HttpMessageConverter,SpringBoot对此做了自动化配置
JacksonHttpMessageConvertersConfiguration
org.springframework.boot.autoconfigure.http.JacksonHttpMessageConvertersConfiguration
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(ObjectMapper.class)
@ConditionalOnBean(ObjectMapper.class)
@ConditionalOnProperty(name = HttpMessageConvertersAutoConfiguration.PREFERRED_MAPPER_PROPERTY,
havingValue = "jackson", matchIfMissing = true)
static class MappingJackson2HttpMessageConverterConfiguration {
@Bean
@ConditionalOnMissingBean(value = MappingJackson2HttpMessageConverter.class,
ignoredType = {
"org.springframework.hateoas.server.mvc.TypeConstrainedMappingJackson2HttpMessageConverter",
"org.springframework.data.rest.webmvc.alps.AlpsJsonHttpMessageConverter" })
MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter(ObjectMapper objectMapper) {
return new MappingJackson2HttpMessageConverter(objectMapper);
}
}
JacksonAutoConfiguration
org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(Jackson2ObjectMapperBuilder.class)
static class JacksonObjectMapperConfiguration {
@Bean
@Primary
@ConditionalOnMissingBean
ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
return builder.createXmlMapper(false).build();
}
}
Gson的自动化配置类
org.springframework.boot.autoconfigure.http.GsonHttpMessageConvertersConfiguration
@Configuration(proxyBeanMethods = false)
@ConditionalOnBean(Gson.class)
@Conditional(PreferGsonOrJacksonAndJsonbUnavailableCondition.class)
static class GsonHttpMessageConverterConfiguration {
@Bean
@ConditionalOnMissingBean
GsonHttpMessageConverter gsonHttpMessageConverter(Gson gson) {
GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
converter.setGson(gson);
return converter;
}
}
自定义SprinBoot的JSON解析
日期格式解析
默认返回的是时间戳类型格式,但是时间戳会少一天需要在数据库连接url上加上时区如:
spring.datasource.url=jdbc:p6spy:mysql://47.100.78.146:3306/mall?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8&autoReconnect=true
- 使用
@JsonFormat注解自定义格式
@JsonFormat(pattern = "yyyy-MM-dd")
private Date birthday;
但是这种要对每个实体类中的日期字段都需要添加此注解不够灵活
- 全局添加
在配置文件中直接添加spring.jackson.date-format=yyyy-MM-dd
NULL字段不返回
- 在接口中如果不需要返回null字段可以使用
@JsonInclude注解
@JsonInclude(JsonInclude.Include.NON_NULL)
private String title;
但是这种要对每个实体类中的字段都需要添加此注解不够灵活
- 全局添加 在配置文件中直接添加
spring.jackson.default-property-inclusion=non_null
自定义字段序列化
自定义null字符串类型字段返回空字符NullStringJsonSerializer序列化
public class NullStringJsonSerializer extends JsonSerializer {
@Override
public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
if (o == null) {
jsonGenerator.writeString("");
}
}
}
自定义null数字类型字段返回0默认值NullIntegerJsonSerializer序列化
public class NullIntegerJsonSerializer extends JsonSerializer {
@Override
public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
if (o == null) {
jsonGenerator.writeNumber(0);
}
}
}
自定义浮点小数类型4舍5入保留2位小数DoubleJsonSerialize序列化
public class DoubleJsonSerialize extends JsonSerializer {
private DecimalFormat df = new DecimalFormat("##.00");
@Override
public void serialize(Object value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
if (value != null) {
jsonGenerator.writeString(NumberUtil.roundStr(value.toString(), 2));
}else{
jsonGenerator.writeString("0.00");
}
}
}
自定义NullArrayJsonSerializer序列化
public class NullArrayJsonSerializer extends JsonSerializer {
@Override
public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
if(o==null){
jsonGenerator.writeStartArray();
}else {
jsonGenerator.writeObject(o);
}
}
}
自定义BeanSerializerModifier使用我们自己的序列化器进行bean序列化
public class MyBeanSerializerModifier extends BeanSerializerModifier {
private JsonSerializer _nullArrayJsonSerializer = new NullArrayJsonSerializer();
private JsonSerializer _nullStringJsonSerializer = new NullStringJsonSerializer();
private JsonSerializer _nullIntegerJsonSerializer = new NullIntegerJsonSerializer();
private JsonSerializer _doubleJsonSerializer = new DoubleJsonSerialize();
@Override
public List changeProperties(SerializationConfig config, BeanDescription beanDesc,
List beanProperties) { // 循环所有的beanPropertyWriter
for (int i = 0; i < beanProperties.size(); i++) {
BeanPropertyWriter writer = (BeanPropertyWriter) beanProperties.get(i);
// 判断字段的类型,如果是array,list,set则注册nullSerializer
if (isArrayType(writer)) { //给writer注册一个自己的nullSerializer
writer.assignNullSerializer(this.defaultNullArrayJsonSerializer());
}
if (isStringType(writer)) {
writer.assignNullSerializer(this.defaultNullStringJsonSerializer());
}
if (isIntegerType(writer)) {
writer.assignNullSerializer(this.defaultNullIntegerJsonSerializer());
}
if (isDoubleType(writer)) {
writer.assignSerializer(this.defaultDoubleJsonSerializer());
}
}
return beanProperties;
} // 判断是什么类型
protected boolean isArrayType(BeanPropertyWriter writer) {
Class clazz = writer.getPropertyType();
return clazz.isArray() || clazz.equals(List.class) || clazz.equals(Set.class);
}
protected boolean isStringType(BeanPropertyWriter writer) {
Class clazz = writer.getPropertyType();
return clazz.equals(String.class);
}
protected boolean isIntegerType(BeanPropertyWriter writer) {
Class clazz = writer.getPropertyType();
return clazz.equals(Integer.class) || clazz.equals(int.class) || clazz.equals(Long.class);
}
protected boolean isDoubleType(BeanPropertyWriter writer) {
Class clazz = writer.getPropertyType();
return clazz.equals(Double.class) || clazz.equals(BigDecimal.class);
}
protected JsonSerializer defaultNullArrayJsonSerializer() {
return _nullArrayJsonSerializer;
}
protected JsonSerializer defaultNullStringJsonSerializer() {
return _nullStringJsonSerializer;
}
protected JsonSerializer defaultNullIntegerJsonSerializer() {
return _nullIntegerJsonSerializer;
}
protected JsonSerializer defaultDoubleJsonSerializer() {
return _doubleJsonSerializer;
}
}
应用我们自己bean序列化使其生效 提供MappingJackson2HttpMessageConverter类
在配置类中提供MappingJackson2HttpMessageConverter类,使用ObjectMapper 做全局的序列化
@Configuration
public class ClassJsonConfiguration {
@Bean
public MappingJackson2HttpMessageConverter mappingJacksonHttpMessageConverter() {
final MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
ObjectMapper mapper = converter.getObjectMapper();
// 为mapper注册一个带有SerializerModifier的Factory,此modifier主要做的事情为:判断序列化类型,根据类型指定为null时的值
mapper.setSerializerFactory(mapper.getSerializerFactory().withSerializerModifier(new MyBeanSerializerModifier()));
return converter;
}
}
此类会代替SpringBoot默认的json解析方案。事实上,此类中起作用的是ObjectMapper 类,因此也可直接配置此类。
@Bean
public ObjectMapper om() {
ObjectMapper mapper = new ObjectMapper();
// 为mapper注册一个带有SerializerModifier的Factory,此modifier主要做的事情为:判断序列化类型,根据类型指定为null时的值
mapper.setSerializerFactory(mapper.getSerializerFactory().withSerializerModifier(new MyBeanSerializerModifier()));
return mapper;
}
通过上面方式自定义序列化,还可以通过注解 @JsonSerialize序列化自定义如:
@Component
public class DoubleSerialize extends JsonSerializer<Double> {
private DecimalFormat df = new DecimalFormat("##.00");
@Override
public void serialize(Double value, JsonGenerator gen, SerializerProvider serializers)
throws IOException, JsonProcessingException {
if(value != null) {
gen.writeString(df.format(value));
}
}
}
然后再需要使用字段上面加上
@JsonSerialize(using = DoubleJsonSerialize.class)
private BigDecimal price;
配置文件jackson详细配置
spring:
jackson:
# 设置属性命名策略,对应jackson下PropertyNamingStrategy中的常量值,SNAKE_CASE-返回的json驼峰式转下划线,json body下划线传到后端自动转驼峰式
property-naming-strategy: SNAKE_CASE
# 全局设置@JsonFormat的格式pattern
date-format: yyyy-MM-dd HH:mm:ss
# 当地时区
locale: zh
# 设置全局时区
time-zone: GMT+8
# 常用,全局设置pojo或被@JsonInclude注解的属性的序列化方式
default-property-inclusion: NON_NULL #不为空的属性才会序列化,具体属性可看JsonInclude.Include
# 常规默认,枚举类SerializationFeature中的枚举属性为key,值为boolean设置jackson序列化特性,具体key请看SerializationFeature源码
serialization:
WRITE_DATES_AS_TIMESTAMPS: true # 返回的java.util.date转换成timestamp
FAIL_ON_EMPTY_BEANS: true # 对象为空时是否报错,默认true
# 枚举类DeserializationFeature中的枚举属性为key,值为boolean设置jackson反序列化特性,具体key请看DeserializationFeature源码
deserialization:
# 常用,json中含pojo不存在属性时是否失败报错,默认true
FAIL_ON_UNKNOWN_PROPERTIES: false
# 枚举类MapperFeature中的枚举属性为key,值为boolean设置jackson ObjectMapper特性
# ObjectMapper在jackson中负责json的读写、json与pojo的互转、json tree的互转,具体特性请看MapperFeature,常规默认即可
mapper:
# 使用getter取代setter探测属性,如类中含getName()但不包含name属性与setName(),传输的vo json格式模板中依旧含name属性
USE_GETTERS_AS_SETTERS: true #默认false
# 枚举类JsonParser.Feature枚举类中的枚举属性为key,值为boolean设置jackson JsonParser特性
# JsonParser在jackson中负责json内容的读取,具体特性请看JsonParser.Feature,一般无需设置默认即可
parser:
ALLOW_SINGLE_QUOTES: true # 是否允许出现单引号,默认false
# 枚举类JsonGenerator.Feature枚举类中的枚举属性为key,值为boolean设置jackson JsonGenerator特性,一般无需设置默认即可
# JsonGenerator在jackson中负责编写json内容,具体特性请看JsonGenerator.Feature
SpringBoot 默认json解析器详解和字段序列化自定义的更多相关文章
- Solr系列五:solr搜索详解(solr搜索流程介绍、查询语法及解析器详解)
一.solr搜索流程介绍 1. 前面我们已经学习过Lucene搜索的流程,让我们再来回顾一下 流程说明: 首先获取用户输入的查询串,使用查询解析器QueryParser解析查询串生成查询对象Query ...
- JAVA中的四种JSON解析方式详解
JAVA中的四种JSON解析方式详解 我们在日常开发中少不了和JSON数据打交道,那么我们来看看JAVA中常用的JSON解析方式. 1.JSON官方 脱离框架使用 2.GSON 3.FastJSON ...
- jmeter之json提取器详解
Json提取器详解 *Apply to:参照正则表达式提取器 *Names of created:自定义变量名. 变量名可以填写多个,变量名之间使用分号进行分隔. 一旦变量名有多个,则下方的json ...
- spring boot2 修改默认json解析器Jackson为fastjson
0.前言 fastjson是阿里出的,尽管近年fasjson爆出过几次严重漏洞,但是平心而论,fastjson的性能的确很有优势,尤其是大数据量时的性能优势,所以fastjson依然是我们的首选:sp ...
- rest_framework之解析器详解 05
解析器就是服务端写api,对于前端用户发来的数据进行解析.解析完之后拿到自己能用数据. 本质就是对请求体中的数据进行解析. django的解析器 post请求过来之后,django 的request. ...
- jmeter后置处理器之Json提取器详解
此提取器用于提取请求返回结果中的某个值或者某一组值,用法比正则表达式要简单,标准写法为$.key,其中key为返回结果map中的一个键,如果是多层则继续用.key进行即可,如果遇到key的value值 ...
- Jmeter之Json提取器详解(史上最全)
参考资料:https://www.bbsmax.com/A/D854lmBw5E/ Jsonpath在线测试:http://jsonpath.com/ 实际工作中用到的一些场景: 提取某个特定的值 提 ...
- SQL解析器详解
1.概述 最近,有同学留言关于SQL解析器方面的问题,今天笔者就为大家分享一下SQL解析器方便的一些内容. 2.内容 2.1 SQL解析器是什么? SQL解析与优化是属于编辑器方面的知识,与C语言这类 ...
- Springboot 过滤器和拦截器详解及使用场景
一.过滤器和拦截器的区别 1.过滤器和拦截器触发时机不一样,过滤器是在请求进入容器后,但请求进入servlet之前进行预处理的.请求结束返回也是,是在servlet处理完后,返回给前端之前. 2.拦截 ...
随机推荐
- 《电容应用分析精粹:从充放电到高速PCB设计》最新勘误表
最新勘误表百度云盘下载 链接: https://pan.baidu.com/s/18yqwnJrCu9oWvFcPiwRWvA 提取码: x3e3 (本勘误表仅包含错误相关部分,不包含对语句的 ...
- scrapy入门到放弃02:整一张架构图,开发一个程序
前言 Scrapy开门篇写了一些纯理论知识,这第二篇就要直奔主题了.先来讲讲Scrapy的架构,并从零开始开发一个Scrapy爬虫程序. 本篇文章主要阐述Scrapy架构,理清开发流程,掌握基本操作. ...
- HDU 4292 Food 多源多汇入门题
Food 有F种食物和D种饮料,每种食物或饮料只能供有限次,且每个人只享用一种食物和一种饮料.现在有n个人,每个人都有自己喜欢的食物种类列表和饮料种类列表,问最多能使几个人同时享用到自己喜欢的食物和饮 ...
- sonarqube 8.9版本配置收邮件提醒
# admin登陆系统后,进入我的账户(每个用户的配置过程类似) sonarqube 8.9版本配置发信请参考我的另一篇博文: 链接如下: https://www.cnblogs.com/cndevo ...
- springboot项目启动,停止,重启
参考博客 https://www.cnblogs.com/c-h-y/p/10460061.html 打包插件,可以指定启动类 <build> <plugins> <pl ...
- ctf实验吧Once More
题目链接:http://ctf5.shiyanbar.com/web/more.php 思路分析:显然是后台逻辑代码. 1.ereg函数有漏洞,可以使用%00截断,这个就做笔记了好吧.这个函数大致意思 ...
- docker起不来报错:Failed to start Docker Application Container Engine.
报错信息如下: [root@localhost localdisk]# systemctl restart docker Job for docker.service failed because t ...
- pxe+kickstart部署多个版本的Linux操作系统(下)---实践篇
我们在企业运维环境中,难免会遇到使用多个Linux操作系统的情况,如果每天都需要安装不同版本的Linux系统的话,那么使用Kickstart只能安装一种版本的Linux系统的方法则显得有些捉襟 ...
- SHELL 变量引用
shell变量的引用非常重要,运用技巧灵活多变 变量的引用主要包含四类:双引号引用.单引号引用.反引号引用.反斜线引用 " " 双引号 屏蔽除美元符号$.反引号( ` )和反斜线( ...
- C语言:函数
1. int scanf ( char * format [ ,argument, ... ]); 返回被赋值的参数的个数