作用:将返回实体类中的属性如果为null 变成""
package com.example.micrweb.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.jackson.JacksonAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.io.IOException; /** * @author hrui * @date 2023/11/23 3:00 */ @Configuration public class JacksonConfiguration { /** * 将返回值json格式化的时候,如果为null 变成"" * 因SpringBoot 返回默认用jackjson格式化 * 而jackson中JacksonAutoConfiguration * 类已经自动配置了一个 ObjectMapper Bean * 这里对ObjectMapper重新定义 */ @Bean public ObjectMapper objectMapper(){ ObjectMapper objectMapper=new ObjectMapper(); //设置null序列化时 为"" objectMapper.getSerializerProvider() .setNullValueSerializer(new JsonSerializer<Object>() { @Override public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { jsonGenerator.writeString(""); } }); return objectMapper; } //JacksonAutoConfiguration }
例如
配置之后