Android Kotlin中Retrofit+Moshi调用API-Football返回空响应
排查Retrofit+Moshi调用API-Football返回空响应的问题
1. 数据类与API响应结构不匹配(最常见原因)
API-Football的get-teams接口返回的JSON外层是**response数组**,而非直接返回单个Team/Venue对象。如果你的TeamResponse直接定义team和venue字段,Moshi会因找不到对应解析路径,导致两个字段都为null。
正确的结构示例:
// 外层响应类,对应API返回的顶层结构 data class ApiResponse( val response: List<TeamWithVenue> ) // 数组内的单个条目,包含球队和场馆数据 data class TeamWithVenue( val team: TeamResponse, val venue: VenueResponse ) // 你的原有TeamResponse、VenueResponse保持不变,但要确保字段名和API返回的key完全一致(注意大小写)
2. Retrofit接口定义错误
检查接口的参数和返回类型:
- 必须在请求头中携带
x-api-key(API-Football强制验证) - 传入的
id必须是球队ID,而非联赛/赛事ID - 返回类型要对应上面的
ApiResponse,不能直接返回TeamResponse
错误示例:
// 错误:直接返回TeamResponse,未匹配外层结构 @GET("teams") suspend fun getTeam(@Query("id") teamId: Int): TeamResponse
正确示例:
@GET("teams") suspend fun getTeam( @Header("x-api-key") apiKey: String, @Query("id") teamId: Int ): ApiResponse
3. Moshi配置缺失关键项
- 必须添加
KotlinJsonAdapterFactory,否则Kotlin数据类的空安全字段无法正确解析 - 若API返回蛇形命名字段(如
team_id),你的数据类用驼峰命名(如teamId)时,要么给字段加@Json(name = "team_id")注解,要么配置Moshi自动转换命名风格
配置示例:
val moshi = Moshi.Builder() .add(KotlinJsonAdapterFactory()) .build() val retrofit = Retrofit.Builder() .baseUrl("https://v3.football.api-sports.io/") .addConverterFactory(MoshiConverterFactory.create(moshi)) .build()
4. API请求验证失败
如果x-api-key无效或未携带,接口会返回空的response数组,最终解析出null的team和venue。可以添加日志拦截器查看完整请求/响应:
val loggingInterceptor = HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY } val okHttpClient = OkHttpClient.Builder() .addInterceptor(loggingInterceptor) .build() // 构建Retrofit时使用这个client val retrofit = Retrofit.Builder() .client(okHttpClient) // 其他配置 .build()
如果日志里的响应JSON中response数组为空,说明API本身未返回数据,大概率是key无效或参数错误。
内容的提问来源于stack exchange,提问作者Dereck Helms
相关产品推荐
相关产品推荐

