今天我们接着上一期来说一下,如果出现空值,SpringBoot会如何处理
在实际项目中,难免会遇到一些 null 值出现,转 json 时是不希望有这些 null 出现的,比如期望所有的 null 在转 json 时都变成""这种空字符串,那该如何做呢?在 Spring Boot 中做一下配置即可。
1.新建一个 jackson 的配置类
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.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 java.io.IOException;
@Configuration *[HTML]: 用于声明当前类是一个配置类,最新的注解为@SpringBootConfiguration
public class JacksonConfig {
@Bean 用于在配置类中,表示方法的返回值是一个受管 bean
@Primary 如果多个配置,则以当前的为主
@ConditionalOnMissingBean(ObjectMapper.class) 条件注解,表示如果受管 bean 中没有 ObjectMapper
类型的对象,则需要构建
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 {
jsonGenerator.writeString(""); 针对 null 内容输出空字符串
}
});
return objectMapper;
}
}
然后修改一下上面返回 map 的接口,将几个值改成 null 测试一下:
@RequestMapping("/map")
public Map<String, Object> getMap() {
Map<String, Object> map = new HashMap<>(3);
User user = new User(1, "张三", null);
map.put("作者信息", user);
map.put("博客地址", "http://blog.zhang.com");
map.put("CSDN 地址", null);
map.put("粉丝数量", 4153);
return map;
}
重启项目再次输入 localhost:8080/json/map,可以看到 jackson 已经将所有 null 字段转成了空字符串了。例如
返回数据为{"作者信息":{"id":1,"username":"张三","password":""},"CSDN 地址":"","粉丝数量":4153,"博客地
址":"http://blog.yan.com"}
配置属性不参与映射输出
@JsonIgnore 指定该属性不参与 JSON 字符串的映射
private String passwo