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

Spring Boot API返回1而非MutualFund JSON对象问题求助

问题排查与解决

你的接口返回数字1而非预期的MutualFund JSON对象,最可能的原因是MutualFundRepo中的方法定义错误,以下是具体排查步骤:

1. 检查Repository方法定义

确认你的MutualFundRepo接口中,findByName方法的返回类型和方法名是否正确:

  • 错误示例(返回计数而非实体):
// 错误:返回符合条件的记录数,会返回数字1
public interface MutualFundRepo extends JpaRepository<MutualFund, Long> {
    Integer findByName(String name);
    // 或者 countByName(String name);
}
  • 正确示例:
// 正确:返回匹配名称的MutualFund实体
public interface MutualFundRepo extends JpaRepository<MutualFund, Long> {
    MutualFund findByName(String name);
    // 或者使用Optional避免空指针:Optional<MutualFund> findByName(String name);
}

2. 验证Repository返回结果

在控制器方法中添加日志,确认repo.findByName(name)的实际返回值:

@RestController
public class MutualFundController {

    @Autowired
    MutualFundRepo repo;

    @GetMapping("/mutualFundNav/{name}")
    MutualFund getMutualFundByName(@PathVariable String name) {
        MutualFund fund = repo.findByName(name);
        System.out.println("Repository返回结果:" + fund); // 查看控制台输出
        return fund;
    }
}

如果控制台输出是数字而非MutualFund对象,说明Repository方法确实写错了。

3. 确保实体类可被序列化

如果Repository返回的是正确对象,但仍未得到预期JSON,检查MutualFund实体类:

  • 确保类中有public的getter方法(或使用Lombok的@Data注解自动生成);
  • 确保类被Spring的JSON序列化器(Jackson)正确识别,比如没有被@JsonIgnore注解覆盖必要字段。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 15:06:39