1. 程式人生 > 程式設計 >jackson設定返回null為空字串的操作

jackson設定返回null為空字串的操作

1、將介面返回的欄位為null的設定為空字串:

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.IOException;
@Configuration
public class CustomConfig {
 @Bean
 public ObjectMapper objectMapper() {
  ObjectMapper objectMapper = new ObjectMapper();
  objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
   @Override
   public void serialize(Object paramT,JsonGenerator paramJsonGenerator,SerializerProvider paramSerializerProvider) throws IOException {
    //設定返回null轉為 空字串""
    paramJsonGenerator.writeString("");
   }
  });
  return objectMapper;
 }
}

2、設定null欄位不返回給前端:

//1.實體上
@JsonInclude(Include.NON_NULL) 
//將該標記放在屬性上,如果該屬性為NULL則不參與序列化 
//如果放在類上邊,那對這個類的全部屬性起作用 
//Include.Include.ALWAYS 預設 
//Include.NON_DEFAULT 屬性為預設值不序列化 
//Include.NON_EMPTY 屬性為 空(“”) 或者為 NULL 都不序列化 
//Include.NON_NULL 屬性為NULL 不序列化 
//2.程式碼上
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL); 
//通過該方法對mapper物件進行設定,所有序列化的物件都將按改規則進行系列化 
//Include.Include.ALWAYS 預設 
//Include.NON_DEFAULT 屬性為預設值不序列化 
//Include.NON_EMPTY 屬性為 空(“”) 或者為 NULL 都不序列化 
//Include.NON_NULL 屬性為NULL 不序列化 

來驗證下結果,很顯然,我們成功了,age、address、sex三個欄位值為null,現在看到是空字串:

jackson設定返回null為空字串的操作

補充知識:SpringBoot Jackson 將null轉字串"" ,List、Array轉[],Int轉0

如下所示:

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
 
import java.io.IOException;
import java.util.Collection;
import java.util.List; 
 
/**
 * 使用官方自帶的json格式類庫,fastjson因為content type問題時不時控制檯報錯、無法直接返回二進位制等問題
 */
class JacksonHttpMessageConverter extends MappingJackson2HttpMessageConverter {
 
  /**
   * 處理陣列型別的null值
   */
  public class NullArrayJsonSerializer extends JsonSerializer<Object> {
 
    @Override
    public void serialize(Object value,JsonGenerator jgen,SerializerProvider provider) throws IOException,JsonProcessingException {
      if (value == null) {
        jgen.writeStartArray();
        jgen.writeEndArray();
      }
    }
  } 
 
  /**
   * 處理字串型別的null值
   */
  public class NullStringJsonSerializer extends JsonSerializer<Object> {
 
    @Override
    public void serialize(Object o,JsonGenerator jsonGenerator,SerializerProvider serializerProvider) throws IOException,JsonProcessingException {
      jsonGenerator.writeString(StringUtils.EMPTY);
    }
  }
 
  /**
   * 處理數字型別的null值
   */
  public class NullNumberJsonSerializer extends JsonSerializer<Object> {
 
    @Override
    public void serialize(Object o,JsonProcessingException {
      jsonGenerator.writeNumber(0);
    }
  }
 
  /**
   * 處理布林型別的null值
   */
  public class NullBooleanJsonSerializer extends JsonSerializer<Object> {
 
    @Override
    public void serialize(Object o,JsonProcessingException {
      jsonGenerator.writeBoolean(false);
    }
  } 
 
  public class MyBeanSerializerModifier extends BeanSerializerModifier { 
 
    @Override
    public List<BeanPropertyWriter> changeProperties(SerializationConfig config,BeanDescription beanDesc,List<BeanPropertyWriter> beanProperties) {
      //迴圈所有的beanPropertyWriter
      for (Object beanProperty : beanProperties) {
        BeanPropertyWriter writer = (BeanPropertyWriter) beanProperty;
        //判斷欄位的型別,如果是array,list,set則註冊nullSerializer
        if (isArrayType(writer)) {
          //給writer註冊一個自己的nullSerializer
          writer.assignNullSerializer(new NullArrayJsonSerializer());
        } else if (isNumberType(writer)) {
          writer.assignNullSerializer(new NullNumberJsonSerializer());
        } else if (isBooleanType(writer)) {
          writer.assignNullSerializer(new NullBooleanJsonSerializer());
        } else if (isStringType(writer)) {
          writer.assignNullSerializer(new NullStringJsonSerializer());
        }
      }
      return beanProperties;
    }
 
    /**
     * 是否是陣列
     */
    private boolean isArrayType(BeanPropertyWriter writer) {
      Class<?> clazz = writer.getType().getRawClass();
      return clazz.isArray() || Collection.class.isAssignableFrom(clazz);
    }
 
    /**
     * 是否是string
     */
    private boolean isStringType(BeanPropertyWriter writer) {
      Class<?> clazz = writer.getType().getRawClass();
      return CharSequence.class.isAssignableFrom(clazz) || Character.class.isAssignableFrom(clazz);
    } 
 
    /**
     * 是否是int
     */
    private boolean isNumberType(BeanPropertyWriter writer) {
      Class<?> clazz = writer.getType().getRawClass();
      return Number.class.isAssignableFrom(clazz);
    }
 
    /**
     * 是否是boolean
     */
    private boolean isBooleanType(BeanPropertyWriter writer) {
      Class<?> clazz = writer.getType().getRawClass();
      return clazz.equals(Boolean.class);
    } 
  }
 
  JacksonHttpMessageConverter() {
    getObjectMapper().setSerializerFactory(getObjectMapper().getSerializerFactory().withSerializerModifier(new MyBeanSerializerModifier()));
  }
 
}

一定要在下面配置訊息轉換器,不然沒效果

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
  @Override
  protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    super.configureMessageConverters(converters);
    converters.add(new JacksonHttpMessageConverter());
  }
 
}

如果想要更豐富的可以在:MyBeanSerializerModifier中自定義。

以上這篇jackson設定返回null為空字串的操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。