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
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,现在看到是空字符串:
补充知识: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;
class JacksonHttpMessageConverter extends MappingJackson2HttpMessageConverter {
public class NullArrayJsonSerializer extends JsonSerializer
一定要在下面配置消息转换器,不然没效果
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
@Override
protected void configureMessageConverters(List> converters) {
super.configureMessageConverters(converters);
converters.add(new JacksonHttpMessageConverter());
}
}
如果想要更丰富的可以在:MyBeanSerializerModifier中自定义。
以上这篇jackson设置返回null为空字符串的操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持考高分网。