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

Spring Controller返回空JSON响应问题求助

问题排查与解决方案

你遇到的问题是Controller返回的ResponseDto明明有值,但Postman收到空JSON对象,这通常是对象序列化失败导致的,以下是常见原因和解决办法:

1. 检查ResponseDto的序列化配置

Spring默认使用Jackson做JSON序列化,它需要满足以下条件才能正确处理对象:

  • 需要序列化的字段要有对应的getter方法,或者用@JsonProperty直接标记字段
  • 类必须包含无参构造函数(如果有带参构造,需显式声明无参构造)
  • 不要对需要返回的字段使用@JsonIgnore注解

示例正确的ResponseDto写法:

public class ResponseDto {
    private String message;
    private Integer code;

    // 必须的无参构造
    public ResponseDto() {}

    // 带参构造可选
    public ResponseDto(String message, Integer code) {
        this.message = message;
        this.code = code;
    }

    // getter方法是Jackson序列化的关键
    public String getMessage() {
        return message;
    }

    public Integer getCode() {
        return code;
    }

    // setter方法可选(仅当需要反序列化时需要)
    public void setMessage(String message) {
        this.message = message;
    }

    public void setCode(Integer code) {
        this.code = code;
    }
}

2. 修复ResponseEntity的泛型声明错误

你当前返回的new ResponseEntity(responseDto, HttpStatus.OK)缺少泛型钻石运算符<>,会导致类型擦除,Spring无法正确识别响应体类型,进而序列化失败。

修改为:

return new ResponseEntity<>(responseDto, HttpStatus.OK);

3. 验证Jackson依赖是否正常引入

如果是Maven项目,确保pom.xml中包含Jackson核心依赖(Spring Boot项目会自动引入,手动管理项目需检查):

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.15.2</version> <!-- 使用与Spring版本兼容的版本 -->
</dependency>

4. 排查全局序列化配置

检查项目中是否有自定义Jackson配置类,比如是否开启了MapperFeature.DEFAULT_VIEW_INCLUSION为false,或者使用了@JsonFilter但未正确配置,导致ResponseDto的字段被意外过滤。

如果有自定义配置,确认规则没有影响目标字段的序列化。

5. 简化测试验证

可以先简化返回逻辑,直接返回ResponseDto对象,验证是否能正常序列化:

public ResponseDto getResponse(@Valid @RequestBody Request request,
                               @RequestHeader(name = "Accept-Language", defaultValue = "en") String locale,
                               @RequestHeader(name = "App-Version", required = false) Integer appVersion)  {
    try {
        ResponseDto responseDto = service.getResponse(request, locale, appVersion);
        log.info("responseDto : {}", responseDto);
        return responseDto;
    }  catch (Exception ex) {
        log.error("Error ",  ex);
        throw  ex;
    }
}

如果这样能返回正确JSON,说明问题出在ResponseEntity的使用上;否则仍需聚焦序列化配置问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 22:21:37