java属性为null,序列化时去掉这个属性
第一种方法:
@JsonInclude(JsonInclude.Include.NON_NULL)
将这个注解加在实体类对应的对象名上面,或者类名上面。
- Include.ALWAYS 属性都序列化
- Include.NON_DEFAULT 属性为默认值不序列化
- Include.NON_EMPTY 属性为 空("") 或者为 NULL 都不序列化
- Include.NON_NULL 属性为NULL 不序列化
如:
@JsonInclude(JsonInclude.Include.NON_NULL)
private String resourceName;
这时候如果resourceName为null 则不会显示该属性。
第二种方法:设置属性默认值
在初始化实体类的时候设置属性默认值
如下:
private String name="";
第三种方法:自定义一个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返回空字符串
*/
@Configuration
public 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的情况下也转成 空字符串,这是个弊端,根据需求而用吧。还是适合自己场景的最好
参考:
https://blog.csdn.net/qq_36802726/article/details/88895444