Springboot2.3.1搭建框架 Controller返回對象自動過濾null屬性字段

請您多多留言指教

框架環境:

springboot2.3.1+mybatisplus3.3.2+jackson2.11.0 全局配置自動過濾null屬性字段

1、application.yml 全局配置 jackson

jackson:
  # 全局設置@JsonFormat的格式pattern
  date-format: yyyy-MM-dd HH:mm:ss
  # 當地時區
  locale: zh
  # 設置全局時區
  time-zone: GMT+8
  serialization:
    #格式化輸出
    indent_output: true
    #忽略無法轉換的對象
    fail_on_empty_beans: false
  deserialization:
    #允許對象忽略json中不存在的屬性
    fail_on_unknown_properties: false
  parser:
    #允許出現特殊字符和轉義符
    allow_unquoted_control_chars: true
    #允許出現單引號
    allow_single_quotes: true
  #如果加該註解的字段爲null,那麼就不序列化這個字段了
  default-property-inclusion: NON_EMPTY

2、類的配置jackson.config

package com.ayiol.business.config;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
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;
import java.io.IOException;

/**
 * Jackson config
 * author LJG
 * date 2020/6/26 20:46
 */
@Configuration
public class JacksonConfig {
    /**
     * 重新注入ObjectMapper
     * 注:使用此方式ObjectMapper,application中Jackson自動失效
     *
     * @param builder
     * @return
     */
    @Bean
    @Primary
    @ConditionalOnMissingBean(ObjectMapper.class)
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();

        // 通過該方法對mapper對象進行設置,所有序列化的對象都將按改規則進行系列化
        // Include.Include.ALWAYS 默認
        // Include.NON_DEFAULT 屬性爲默認值不序列化
        // Include.NON_EMPTY 屬性爲 空("") 或者爲 NULL 都不序列化,則返回的json無此屬性字段
        // Include.NON_NULL 屬性爲NULL 不序列化
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
        // 反序列化時 忽略匹配不到的屬性字段
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        // 允許出現單引號
        objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        // 字段保留,將null值轉爲""
        objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
            @Override
            public void serialize(Object o, JsonGenerator jsonGenerator,
                                  SerializerProvider serializerProvider)
                    throws IOException {
                jsonGenerator.writeString("");
            }
        });
        return objectMapper;
    }
}

注:紅色標記爲重點,這種配置按需求使用(本人未使用:因需要返回相關爲null的屬性字段)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章