You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将响应对象的字符串参数设置为null?赋值null却返回空字符串的解决方法

问题:如何在响应对象中正确设置字符串参数为null?

我在返回UserDto对象时,明明把字符串属性都设为了null,但响应里却变成了空字符串,只有Long类型的id正常返回null,请问怎么解决这个问题?

我的代码:

UserDto类

public class UserDto {
    Long id;
    String firstname;
    String lastname;
    // getter, setters
}

Service层代码

UserDto userDto = new UserDto();
userDto.setId(null);
userDto.setFirstname(null);
userDto.setLastname(null);
return userDto;

实际得到的响应

{
    "id": null,
    "firstName": "",
    "lastName": "",
}

解决方案

这个问题的核心是你的JSON序列化框架(几乎可以肯定是Jackson,Spring Boot默认用它)被配置了将null字符串自动序列化为空字符串的特性,而Long等引用类型的null不受这个配置影响,所以能正常返回null。下面提供几种解决方式:

1. 全局修改配置(Spring Boot项目推荐)

如果希望整个项目的null字符串都返回null而不是空字符串,直接在配置文件里修改Jackson的序列化规则:

application.properties

spring.jackson.serialization.write-null-string-as-empty=false

application.yml

spring:
  jackson:
    serialization:
      write-null-string-as-empty: false

2. 针对单个类/属性配置

如果只想让特定类或属性返回null字符串,不想修改全局配置,可以用Jackson的注解来控制:

方式一:给整个类添加注解

import com.fasterxml.jackson.annotation.JsonInclude;

// 确保null值被序列化输出,不会被过滤也不会转为空字符串
@JsonInclude(JsonInclude.Include.ALWAYS)
public class UserDto {
    Long id;
    String firstname;
    String lastname;
    // getter, setters
}

方式二:给单个属性添加注解

如果只有部分属性需要返回null,只给对应属性加注解即可:

public class UserDto {
    Long id;
    
    @JsonInclude(JsonInclude.Include.ALWAYS)
    String firstname;
    
    @JsonInclude(JsonInclude.Include.ALWAYS)
    String lastname;
    // getter, setters
}

3. 检查自定义ObjectMapper配置

如果项目里有自定义的ObjectMapper配置类,要确保没有开启WRITE_NULL_STRING_AS_EMPTY特性,或者手动关闭它:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class JacksonConfig {
    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        // 关闭"将null字符串转为空字符串"的特性
        objectMapper.configure(SerializationFeature.WRITE_NULL_STRING_AS_EMPTY, false);
        return objectMapper;
    }
}

内容的提问来源于stack exchange,提问作者Alex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 03:42:43