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
相关产品推荐
相关产品推荐

