亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

springboot響應(yīng)json?null值過濾方式

 更新時(shí)間:2021年11月30日 08:57:49   作者:CR2018  
這篇文章主要介紹了springboot響應(yīng)json?null值過濾方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

springboot響應(yīng)json null值過濾

spring:
  jackson:
    default-property-inclusion: non_null

只需要在application.yml中配置以上內(nèi)容即可。

springboot處理返回json的null值

在后端數(shù)據(jù)接口項(xiàng)目開發(fā)中,經(jīng)常遇到返回的數(shù)據(jù)中有null值,導(dǎo)致前端需要進(jìn)行判斷處理,否則容易出現(xiàn)undefined的情況,如何便捷的將null值轉(zhuǎn)換為空字符串?

以SpringBoot項(xiàng)目為例,SSM同理。

1、新建配置類(JsonConfig.java)

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
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;
@Configuration
public class JsonConfig {
    @Bean
    @Primary
    @ConditionalOnMissingBean(ObjectMapper.class)
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder)
    {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        // 通過該方法對(duì)mapper對(duì)象進(jìn)行設(shè)置,所有序列化的對(duì)象都將按改規(guī)則進(jìn)行系列化
        // Include.Include.ALWAYS 默認(rèn)
        // Include.NON_DEFAULT 屬性為默認(rèn)值不序列化
        // Include.NON_EMPTY 屬性為 空("") 或者為 NULL 都不序列化,則返回的json是沒有這個(gè)字段的。這樣對(duì)移動(dòng)端會(huì)更省流量
        // Include.NON_NULL 屬性為NULL 不序列化,就是為null的字段不參加序列化
        //objectMapper.setSerializationInclusion(Include.NON_EMPTY);
        // 字段保留,將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;
    }
}

2、在啟動(dòng)類Application中

記得添加Scan注解,防止無法掃描到配置類。

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論