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


現在項目都是前后端分離的,返回的數據都是使用json,但有些接口的返回值存在 null或者"",這種字段不僅影響理解,還浪費帶寬,需要統一做一下處理,不返回空字段,或者把NULL轉成“”,spring 內置的json處理框架是Jackson,對它配置后可以去除

Jackson ObjectMapper

通過自定義配置該組件可以選擇性序列化返回的JSON

通過官網可以知道:https://docs.spring.io/spring-boot/docs/2.1.1.RELEASE/reference/htmlsingle/#howto-customize-the-jackson-objectmapper

 

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 不序列化
}

替換非空:

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;
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM