jackson 中对 null 的处理
在实际项目中,我们难免会遇到一些 null 值出现,我们转 json 时,是不希望有这些 null 出现的,比如我们期望所有的 null 在转 json 时都变成 "" 这种空字符串,那怎么做 呢?在 Spring Boot 中,我们做一下配置即可,新建一个 jackson 的配
package com.itcodai.course02.config;
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
public class JacksonConfig {
@Bean
@Primary
@ConditionalOnMissingBean(ObjectMapper.class)
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
ObjectMapper objectMapper = builder.createXmlMapper(false).build();
objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer
然后我们修改一下上面返回 map 的接口,将几个值改成 null 测试一下:
@RequestMapping("/map")
public Map getMap() {
Map map = new HashMap<>(3);
User user = new User(1, "倪升武", null);
map.put("作者信息", user);
map.put("博客地址", "http://blog.itcodai.com");
map.put("CSDN 地址", null);
map.put("粉丝数量", 4153);
return map;
}
重启项目,再次输入:localhost:8080/json/map,可以看到 jackson 已经将所有
null 字段转成了空字符串了。
{"作者信息":{"id":1,"username":"倪升武","password":""},"CSDN 地址":"","粉
丝数量":4153,"博客地址":"http://blog.itcodai.com"}