SpringBoot 默认json解析器详解和字段序列化自定义

本文主要是介绍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自动配置了JacksonGson的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@ConditionalOnMissingBeanObjectMapper 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@ConditionalOnMissingBeanGsonHttpMessageConverter 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
  1. 使用@JsonFormat注解自定义格式
	@JsonFormat(pattern = "yyyy-MM-dd")private Date birthday;

但是这种要对每个实体类中的日期字段都需要添加此注解不够灵活

  1. 全局添加
    在配置文件中直接添加spring.jackson.date-format=yyyy-MM-dd

NULL字段不返回

  1. 在接口中如果不需要返回null字段可以使用@JsonInclude注解
    @JsonInclude(JsonInclude.Include.NON_NULL)private String title;

但是这种要对每个实体类中的字段都需要添加此注解不够灵活

  1. 全局添加 在配置文件中直接添加spring.jackson.default-property-inclusion=non_null

自定义字段序列化

自定义null字符串类型字段返回空字符NullStringJsonSerializer序列化

public class NullStringJsonSerializer extends JsonSerializer {@Overridepublic void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {if (o == null) {jsonGenerator.writeString("");}}
}

自定义null数字类型字段返回0默认值NullIntegerJsonSerializer序列化

public class NullIntegerJsonSerializer extends JsonSerializer {@Overridepublic 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");@Overridepublic 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 {@Overridepublic 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();@Overridepublic List changeProperties(SerializationConfig config, BeanDescription beanDesc,List beanProperties) { // 循环所有的beanPropertyWriterfor (int i = 0; i < beanProperties.size(); i++) {BeanPropertyWriter writer = (BeanPropertyWriter) beanProperties.get(i);// 判断字段的类型,如果是array,list,set则注册nullSerializerif (isArrayType(writer)) { //给writer注册一个自己的nullSerializerwriter.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 {@Beanpublic 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 类,因此也可直接配置此类。

 @Beanpublic 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");  @Overridepublic 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的格式patterndate-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转换成timestampFAIL_ON_EMPTY_BEANS: true # 对象为空时是否报错,默认true# 枚举类DeserializationFeature中的枚举属性为key,值为boolean设置jackson反序列化特性,具体key请看DeserializationFeature源码deserialization:# 常用,json中含pojo不存在属性时是否失败报错,默认trueFAIL_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解析器详解和字段序列化自定义的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1066719

相关文章

使用Java将各种数据写入Excel表格的操作示例

《使用Java将各种数据写入Excel表格的操作示例》在数据处理与管理领域,Excel凭借其强大的功能和广泛的应用,成为了数据存储与展示的重要工具,在Java开发过程中,常常需要将不同类型的数据,本文... 目录前言安装免费Java库1. 写入文本、或数值到 Excel单元格2. 写入数组到 Excel表格

redis中使用lua脚本的原理与基本使用详解

《redis中使用lua脚本的原理与基本使用详解》在Redis中使用Lua脚本可以实现原子性操作、减少网络开销以及提高执行效率,下面小编就来和大家详细介绍一下在redis中使用lua脚本的原理... 目录Redis 执行 Lua 脚本的原理基本使用方法使用EVAL命令执行 Lua 脚本使用EVALSHA命令

Java并发编程之如何优雅关闭钩子Shutdown Hook

《Java并发编程之如何优雅关闭钩子ShutdownHook》这篇文章主要为大家详细介绍了Java如何实现优雅关闭钩子ShutdownHook,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起... 目录关闭钩子简介关闭钩子应用场景数据库连接实战演示使用关闭钩子的注意事项开源框架中的关闭钩子机制1.

Maven中引入 springboot 相关依赖的方式(最新推荐)

《Maven中引入springboot相关依赖的方式(最新推荐)》:本文主要介绍Maven中引入springboot相关依赖的方式(最新推荐),本文给大家介绍的非常详细,对大家的学习或工作具有... 目录Maven中引入 springboot 相关依赖的方式1. 不使用版本管理(不推荐)2、使用版本管理(推

Java 中的 @SneakyThrows 注解使用方法(简化异常处理的利与弊)

《Java中的@SneakyThrows注解使用方法(简化异常处理的利与弊)》为了简化异常处理,Lombok提供了一个强大的注解@SneakyThrows,本文将详细介绍@SneakyThro... 目录1. @SneakyThrows 简介 1.1 什么是 Lombok?2. @SneakyThrows

在 Spring Boot 中实现异常处理最佳实践

《在SpringBoot中实现异常处理最佳实践》本文介绍如何在SpringBoot中实现异常处理,涵盖核心概念、实现方法、与先前查询的集成、性能分析、常见问题和最佳实践,感兴趣的朋友一起看看吧... 目录一、Spring Boot 异常处理的背景与核心概念1.1 为什么需要异常处理?1.2 Spring B

SpringBoot3.4配置校验新特性的用法详解

《SpringBoot3.4配置校验新特性的用法详解》SpringBoot3.4对配置校验支持进行了全面升级,这篇文章为大家详细介绍了一下它们的具体使用,文中的示例代码讲解详细,感兴趣的小伙伴可以参考... 目录基本用法示例定义配置类配置 application.yml注入使用嵌套对象与集合元素深度校验开发

Python中的Walrus运算符分析示例详解

《Python中的Walrus运算符分析示例详解》Python中的Walrus运算符(:=)是Python3.8引入的一个新特性,允许在表达式中同时赋值和返回值,它的核心作用是减少重复计算,提升代码简... 目录1. 在循环中避免重复计算2. 在条件判断中同时赋值变量3. 在列表推导式或字典推导式中简化逻辑

如何在 Spring Boot 中实现 FreeMarker 模板

《如何在SpringBoot中实现FreeMarker模板》FreeMarker是一种功能强大、轻量级的模板引擎,用于在Java应用中生成动态文本输出(如HTML、XML、邮件内容等),本文... 目录什么是 FreeMarker 模板?在 Spring Boot 中实现 FreeMarker 模板1. 环

SpringMVC 通过ajax 前后端数据交互的实现方法

《SpringMVC通过ajax前后端数据交互的实现方法》:本文主要介绍SpringMVC通过ajax前后端数据交互的实现方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价... 在前端的开发过程中,经常在html页面通过AJAX进行前后端数据的交互,SpringMVC的controll