spring boot 接口返回值去掉爲null的字段

如今項目都是先後端分離的,返回的數據都是使用json,但有些接口的返回值存在 null或者"",這種字段不只影響理解,還浪費帶寬,須要統一作一下處理,不返回空字段,或者把NULL轉成「」,spring 內置的json處理框架是Jackson,對它配置後能夠去除html

Jackson ObjectMapper

經過自定義配置該組件能夠選擇性序列化返回的JSONspring

經過官網能夠知道:https://docs.spring.io/spring-boot/docs/2.1.1.RELEASE/reference/htmlsingle/#howto-customize-the-jackson-objectmapperjson

 

Spring MVC(客戶端和服務器端)用於HttpMessageConverters在HTTP交換中協商內容轉換。若是Jackson在類路徑上,您已經得到了提供的默認轉換器Jackson2ObjectMapperBuilder,其中一個實例是爲您自動配置的。
Spring Boot還具備一些功能,能夠更輕鬆地自定義此行爲。後端

新建配置類:(去掉 null 或 "" 字段)服務器

package com.zpark.tools;

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 cosmo
 * @Title: JacksonConfig
 * @ProjectName  
 * @Description:  
 * @date  
 */

@Configuration
public class JacksonConfig {
   
    @Bean
    @Primary
    @ConditionalOnMissingBean(ObjectMapper.class)
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        //經過該方法對mapper對象進行設置,全部序列化的對象都將按改規則進行系列化,屬性爲NULL 不序列化
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        return objectMapper;
    }
    //Include.Include.ALWAYS 默認
    //Include.NON_DEFAULT 屬性爲默認值不序列化
    //nclude.NON_EMPTY       屬性爲 空("") 或者爲 NULL 都不序列化
    //Include.NON_NULL       屬性爲NULL 不序列化
}

替換非空:app

public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
            @Override
            public void serialize(Object o, JsonGenerator jsonGenerator,SerializerProvider serializerProvider)throws IOException, JsonProcessingException {
                jsonGenerator.writeString("");
            }
        });
        return objectMapper;
    }
相關文章
相關標籤/搜索