簡(jiǎn)介
在前后端分離的微服務(wù)時(shí)代,后端API需要良好的規(guī)范。本篇主要將一個(gè)數(shù)據(jù)返回時(shí)的一個(gè)小技巧-- 過(guò)濾為空字段
解決痛點(diǎn):將有效解決數(shù)據(jù)傳輸過(guò)程中的流量浪費(fèi)。
組件簡(jiǎn)介
Jackson ObjectMapper
通過(guò)自定義配置該組件可以選擇性序列化返回的JSON。
官方解釋
Spring MVC(客戶端和服務(wù)器端)用于HttpMessageConverters在HTTP交換中協(xié)商內(nèi)容轉(zhuǎn)換。如果Jackson在類路徑上,您已經(jīng)獲得了提供的默認(rèn)轉(zhuǎn)換器 Jackson2ObjectMapperBuilder ,其中一個(gè)實(shí)例是為您自動(dòng)配置的。
Spring Boot還具有一些功能,可以更輕松地自定義此行為。
實(shí)戰(zhàn)代碼
創(chuàng)建配置類
首先創(chuàng)建一個(gè)配置類,加入定義為: JacksonConfig
代碼清單
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
/**
* @author Han Yahong<hyhvpn@126.com>
* @program 51-baojiadan-service
* @description 返回json空值去掉null和""
* @create 2018-07-26 11:04
*/
@Configuration
public class JacksonConfig {
@Bean
@Primary
@ConditionalOnMissingBean(ObjectMapper.class)
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
ObjectMapper objectMapper = builder.createXmlMapper(false).build();
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
return objectMapper;
}
}
代碼解釋:以上就是全部代碼,通過(guò)注解@Configuration 注入后可自動(dòng)配置。
關(guān)鍵點(diǎn):objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
通過(guò)該方法對(duì)mapper對(duì)象進(jìn)行設(shè)置,所有序列化的對(duì)象都將按改規(guī)則進(jìn)行系列化。
其中枚舉屬性:JsonInclude.Include.NON_NULL有以下選擇:
| 屬性 | 使用場(chǎng)景 |
|---|---|
Include.Include.ALWAYS |
默認(rèn) |
Include.NON_DEFAULT |
屬性為默認(rèn)值不序列化 |
Include.NON_EMPTY |
屬性為 空("") 或者為 NULL 都不序列化 |
Include.NON_NULL |
屬性為NULL 不序列化 |
替換非空
可通過(guò)自定義替換原有制定值。代碼如下:
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
ObjectMapper objectMapper = builder.createXmlMapper(false).build();
// 字段保留,將null值轉(zhuǎn)為""
objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
@Override
public void serialize(Object o, JsonGenerator jsonGenerator,
SerializerProvider serializerProvider)
throws IOException, JsonProcessingException {
jsonGenerator.writeString("");
}
});
return objectMapper;
}
本文結(jié)束
BLOG官網(wǎng)地址:https://www.hanyahong.com