Spring Boot如何将JSON响应中的null对象序列化为空字符串?
在Spring Boot中将null对象序列化为空字符串的解决方案
我来帮你搞定这个需求!要把JSON响应里的null值转成空字符串,同时保留属性不被排除,不用JsonInclude.Include.NON_NULL的话,自定义Jackson序列化器是最靠谱的办法,下面是具体实现步骤:
1. 自定义Null转空字符串的序列化器
先写一个序列化器类,专门处理null值的序列化逻辑:
import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import java.io.IOException; public class NullAsEmptyStringSerializer extends JsonSerializer<Object> { @Override public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException { // 当值为null时输出空字符串,否则正常序列化原对象 gen.writeString(value == null ? "" : value.toString()); } }
如果你只想针对String类型的null做转换,把上面的Object.class换成String.class即可,这样其他类型(比如Integer、Boolean)的null会保持原样。
2. 配置Jackson的ObjectMapper
接下来在Spring配置类里注册这个序列化器,注意Spring Boot 2.x之后WebMvcConfigurerAdapter已经被废弃,直接实现WebMvcConfigurer接口就行:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; @Configuration public class WebConfig implements WebMvcConfigurer { @Bean public ObjectMapper objectMapper() { SimpleModule module = new SimpleModule(); // 注册自定义序列化器,这里用Object.class会处理所有类型的null转空字符串 module.addSerializer(Object.class, new NullAsEmptyStringSerializer()); return Jackson2ObjectMapperBuilder.json() .modules(module) .build(); } }
或者你也可以通过配置Jackson2ObjectMapperBuilder的方式来注册模块:
@Bean public Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder() { return new Jackson2ObjectMapperBuilder() .modules(new SimpleModule() {{ addSerializer(Object.class, new NullAsEmptyStringSerializer()); }}); }
3. 测试效果
比如你的响应实体类是这样的:
public class MyResponse { private String myProperty; private Integer anotherProperty; // getter、setter和构造方法省略 }
当myProperty为null时,接口返回的JSON就会是:
{ "myProperty": "", "anotherProperty": null }
完全符合你想要的效果——保留属性,同时把目标null转成空字符串。
内容的提问来源于stack exchange,提问作者Josh Maag
相关产品推荐
相关产品推荐

