现在项目都是前后端分离的,返回的数据都是使用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; }
原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/18579.html