jackson 中对 null 的处理

前情提要:

在项目中如何将null值转变为空字符串呢?


@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<Object>() {
            @Override
            public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
                jsonGenerator.writeString("");
            }
        });
        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);
  return map;
}

重启项目,再次输入:localhost:8080/json/map,可以看到 jackson 已经将所有
null 字段转成了空字符串了。

{"作者信息":{"id":1,"username":"小刘","password":""}}
posted @ 2022-02-09 15:11  帅气的涛啊  阅读(1184)  评论(0编辑  收藏  举报