第一种方法:
@JsonInclude(JsonInclude.Include.NON_NULL)
将这个注解加在实体类对应的对象名上面,或者类名上面。
Include.ALWAYS 属性都序列化
Include.NON_DEFAULT 属性为默认值不序列化
Include.NON_EMPTY 属性为 空(””) 或者为 NULL 都不序列化
Include.NON_NULL 属性为NULL 不序列化
如:
private Integer id;@JsonInclude(JsonInclude.Include.NON_NULL)private String resourceName;
这时候如果resourceName为null 则不会显示该属性。
这个方法缺点就是就是如果为空整个属性就没了,下面介绍一种讲null转””的方法。
第二种方法:自定义一个objectmapper
import java.io.IOException;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 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;/** * null返回空字符串 */@Configurationpublic class JacksonConfig { @Bean @Primary @ConditionalOnMissingBean(ObjectMapper.class) public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) { ObjectMapper objectMapper = builder.createXmlMapper(false).build(); SerializerProvider serializerProvider = objectMapper.getSerializerProvider(); serializerProvider.setNullValueSerializer(new JsonSerializer<Object>() { @Override public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException { jsonGenerator.writeString(""); } }); return objectMapper; }}
注意但是这个方法会把对象为空,list ,map ,枚举 为 null的情况下也转成 空字符串,这是个弊端,根据需求而用吧。
第三种方法:直接设置属性默认值
就是在初始化实体类的时候设置属性默认值
如:
private String name="";