Java对象为空时,将null转换为"" 保存值为空的属性


Java对象为空时,不显示该对象属性,或者将null转换为""
第一种方法:
@JsonInclude(JsonInclude.Include.NON_NULL)
private String resourceName;
Include.ALWAYS 属性都序列化
Include.NON_DEFAULT 属性为默认值不序列化
Include.NON_EMPTY 属性为 空("") 或者为 NULL 都不序列化
Include.NON_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返回空字符串
*/
@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的情况下也转成 空字符串,这是个弊端,根据需求而用吧。

第三种方法:直接设置属性默认值

就是在初始化实体类的时候设置属性默认值

如:

private String name="";

———————————————— https://blog.csdn.net/qq_36802726/article/details/88895444

java 查询时实体不返回字段为空的数据
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class VAuth extends Auth {

}


list转json时保存值为空的属性
String param=JSONObject.toJSONString(fhlist, SerializerFeature.WriteMapNullValue);
效果:[{"channel_id":1,"channel_name":"测试通道","channel_Url":null}]

原文地址:https://www.cnblogs.com/hahajava/p/13293343.html