前言
在我們開發(fā)項(xiàng)目API接口的時(shí)候落午,一些沒有數(shù)據(jù)的字段會(huì)默認(rèn)返回NULL,數(shù)字類型也會(huì)是NULL,這個(gè)時(shí)候前端希望字符串能夠統(tǒng)一返回空字符摄乒,數(shù)字默認(rèn)返回0瑰煎,那我們就需要自定義json序列化處理
SpringBoot默認(rèn)的json解析方案
我們知道在springboot中有默認(rèn)的json解析器屹篓,Spring Boot 中默認(rèn)使用的 Json 解析技術(shù)框架是 jackson
。我們點(diǎn)開 pom.xml 中的 spring-boot-starter-web
依賴撇吞,可以看到一個(gè) 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 中對(duì)依賴都做了很好的封裝俗冻,可以看到很多 spring-boot-starter-xxx 系列的依賴,這是 Spring Boot 的特點(diǎn)之一牍颈,不需要人為去引入很多相關(guān)的依賴了迄薄,starter-xxx 系列直接都包含了所必要的依賴,所以我們?cè)俅吸c(diǎn)進(jìn)去上面這個(gè) 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>
我們?cè)赾ontroller中返回json時(shí)候通過注解@ResponseBody
就可以自動(dòng)幫我們將服務(wù)端返回的對(duì)象序列化成json字符串讥蔽,在傳遞json body參數(shù)時(shí)候 通過在對(duì)象參數(shù)上@RequestBody
注解就可以自動(dòng)幫我們將前端傳過來的json字符串反序列化成java對(duì)象
這些功能都是通過HttpMessageConverter
這個(gè)消息轉(zhuǎn)換工具類來實(shí)現(xiàn)的
SpringMVC自動(dòng)配置了Jackson
和Gson
的HttpMessageConverter,SpringBoot對(duì)此做了自動(dòng)化配置
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的自動(dòng)化配置類
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解析
日期格式解析
默認(rèn)返回的是時(shí)間戳類型格式画机,但是時(shí)間戳?xí)僖惶煨枰跀?shù)據(jù)庫連接url上加上時(shí)區(qū)如:
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;
但是這種要對(duì)每個(gè)實(shí)體類中的日期字段都需要添加此注解不夠靈活
- 全局添加
在配置文件中直接添加spring.jackson.date-format=yyyy-MM-dd
NULL字段不返回
- 在接口中如果不需要返回null字段可以使用
@JsonInclude
注解
@JsonInclude(JsonInclude.Include.NON_NULL)
private String title;
但是這種要對(duì)每個(gè)實(shí)體類中的字段都需要添加此注解不夠靈活
- 全局添加 在配置文件中直接添加
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數(shù)字
類型字段返回0默認(rèn)值NullIntegerJsonSerializer
序列化
public class NullIntegerJsonSerializer extends JsonSerializer {
@Override
public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
if (o == null) {
jsonGenerator.writeNumber(0);
}
}
}
自定義浮點(diǎn)小數(shù)
類型4舍5入保留2位小數(shù)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
使用我們自己的序列化器進(jìn)行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) { // 循環(huán)所有的beanPropertyWriter
for (int i = 0; i < beanProperties.size(); i++) {
BeanPropertyWriter writer = (BeanPropertyWriter) beanProperties.get(i);
// 判斷字段的類型冶伞,如果是array,list步氏,set則注冊(cè)nullSerializer
if (isArrayType(writer)) { //給writer注冊(cè)一個(gè)自己的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;
}
}
應(yīng)用我們自己bean序列化使其生效 提供MappingJackson2HttpMessageConverter類
在配置類中提供MappingJackson2HttpMessageConverter類碰缔,使用ObjectMapper 做全局的序列化
@Configuration
public class ClassJsonConfiguration {
@Bean
public MappingJackson2HttpMessageConverter mappingJacksonHttpMessageConverter() {
final MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
ObjectMapper mapper = converter.getObjectMapper();
// 為mapper注冊(cè)一個(gè)帶有SerializerModifier的Factory,此modifier主要做的事情為:判斷序列化類型戳护,根據(jù)類型指定為null時(shí)的值
mapper.setSerializerFactory(mapper.getSerializerFactory().withSerializerModifier(new MyBeanSerializerModifier()));
return converter;
}
}
此類會(huì)代替SpringBoot默認(rèn)的json解析方案。事實(shí)上瀑焦,此類中起作用的是ObjectMapper
類腌且,因此也可直接配置此類。
@Bean
public ObjectMapper om() {
ObjectMapper mapper = new ObjectMapper();
// 為mapper注冊(cè)一個(gè)帶有SerializerModifier的Factory榛瓮,此modifier主要做的事情為:判斷序列化類型铺董,根據(jù)類型指定為null時(shí)的值
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詳細(xì)配置
spring:
jackson:
# 設(shè)置屬性命名策略,對(duì)應(yīng)jackson下PropertyNamingStrategy中的常量值禀晓,SNAKE_CASE-返回的json駝峰式轉(zhuǎn)下劃線精续,json body下劃線傳到后端自動(dòng)轉(zhuǎn)駝峰式
property-naming-strategy: SNAKE_CASE
# 全局設(shè)置@JsonFormat的格式pattern
date-format: yyyy-MM-dd HH:mm:ss
# 當(dāng)?shù)貢r(shí)區(qū)
locale: zh
# 設(shè)置全局時(shí)區(qū)
time-zone: GMT+8
# 常用,全局設(shè)置pojo或被@JsonInclude注解的屬性的序列化方式
default-property-inclusion: NON_NULL #不為空的屬性才會(huì)序列化,具體屬性可看JsonInclude.Include
# 常規(guī)默認(rèn),枚舉類SerializationFeature中的枚舉屬性為key粹懒,值為boolean設(shè)置jackson序列化特性,具體key請(qǐng)看SerializationFeature源碼
serialization:
WRITE_DATES_AS_TIMESTAMPS: true # 返回的java.util.date轉(zhuǎn)換成timestamp
FAIL_ON_EMPTY_BEANS: true # 對(duì)象為空時(shí)是否報(bào)錯(cuò)重付,默認(rèn)true
# 枚舉類DeserializationFeature中的枚舉屬性為key,值為boolean設(shè)置jackson反序列化特性,具體key請(qǐng)看DeserializationFeature源碼
deserialization:
# 常用,json中含pojo不存在屬性時(shí)是否失敗報(bào)錯(cuò),默認(rèn)true
FAIL_ON_UNKNOWN_PROPERTIES: false
# 枚舉類MapperFeature中的枚舉屬性為key凫乖,值為boolean設(shè)置jackson ObjectMapper特性
# ObjectMapper在jackson中負(fù)責(zé)json的讀寫确垫、json與pojo的互轉(zhuǎn)弓颈、json tree的互轉(zhuǎn),具體特性請(qǐng)看MapperFeature,常規(guī)默認(rèn)即可
mapper:
# 使用getter取代setter探測(cè)屬性,如類中含getName()但不包含name屬性與setName()删掀,傳輸?shù)膙o json格式模板中依舊含name屬性
USE_GETTERS_AS_SETTERS: true #默認(rèn)false
# 枚舉類JsonParser.Feature枚舉類中的枚舉屬性為key翔冀,值為boolean設(shè)置jackson JsonParser特性
# JsonParser在jackson中負(fù)責(zé)json內(nèi)容的讀取,具體特性請(qǐng)看JsonParser.Feature,一般無需設(shè)置默認(rèn)即可
parser:
ALLOW_SINGLE_QUOTES: true # 是否允許出現(xiàn)單引號(hào),默認(rèn)false
# 枚舉類JsonGenerator.Feature枚舉類中的枚舉屬性為key披泪,值為boolean設(shè)置jackson JsonGenerator特性纤子,一般無需設(shè)置默認(rèn)即可
# JsonGenerator在jackson中負(fù)責(zé)編寫json內(nèi)容,具體特性請(qǐng)看JsonGenerator.Feature