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

ResponseEntity未返回预期结果:Postman仅显示空JSON对象

问题原因及解决方案

核心原因

自定义HttpResponse类的字段使用protected修饰符,Jackson默认无法序列化非public字段(即便Lombok生成了getter方法,也可能因访问权限或Jackson默认配置导致无法识别);再加上@JsonInclude(JsonInclude.Include.NON_DEFAULT)注解会排除与默认值一致的字段,最终导致序列化后返回空对象。而控制台能打印数据是因为Lombok的@Data注解生成了toString()方法,该方法可正常访问protected字段。

解决方案

方案1:将字段修饰符改为public

直接把HttpResponse中的所有字段从protected改为public,让Jackson可以直接访问字段完成序列化:

@Data
@SuperBuilder
@JsonInclude(JsonInclude.Include.NON_DEFAULT)
open class HttpResponse (

    var timestamp: String? = LocalDateTime.now().toString(),
    var statusCode: Int? = null,
    var status: HttpStatus? = null,
    var message: String? = "",
    var developerMessage: String = "",
    var path: String = "",
    var requestMethod: String = "",
    var daten: Map<Any, Any>

)

方案2:保留protected修饰符,添加@JsonProperty注解

如果需要保留protected字段修饰,给每个字段添加@JsonProperty注解,明确告知Jackson需要序列化这些字段:

@Data
@SuperBuilder
@JsonInclude(JsonInclude.Include.NON_DEFAULT)
open class HttpResponse (

    @JsonProperty
    protected var timestamp: String? = LocalDateTime.now().toString(),
    @JsonProperty
    protected var statusCode: Int? = null,
    @JsonProperty
    protected var status: HttpStatus? = null,
    @JsonProperty
    protected var message: String? = "",
    @JsonProperty
    protected var developerMessage: String = "",
    @JsonProperty
    protected var path: String = "",
    @JsonProperty
    protected var requestMethod: String = "",
    @JsonProperty
    protected var daten: Map<Any, Any>

)

额外检查点

  • 确认User类的字段可正常序列化(控制台能打印说明newUser数据正常,此点大概率无需调整)
  • Spring Boot 2.x+版本的Jackson默认配置无需额外修改,上述方案即可解决问题

内容的提问来源于stack exchange,提问作者Captai-N

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 21:57:26