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

Retrofit调用POGO API解析JSON响应返回null问题求助

问题根因

你遇到的解析返回null的核心原因是**自定义数据模型与API实际返回的JSON结构完全不匹配,Gson无法找到对应字段完成映射。

具体错误点

  • 你请求的released_pokemon.json接口根节点直接返回Map<String, 宝可梦对象>结构,不存在你定义的ListOfReleasedPokemon类里的releasedPokemon外层字段,也没有列表结构。
  • 你定义的ListOfReleasedPokemon、PokemonResponse两个数据类没有对应的JSON结构匹配,属于多余定义。
修复方案

1. 修改Retrofit API接口定义

直接使用与返回结构匹配的类型作为返回值:

interface PogoApi {
    @GET("released_pokemon.json")
    suspend fun getReleasedPokemon(): Map<String, ReleasedPokemonModel>
}

2. 调整仓库层接收逻辑

将返回的Map转为你需要的列表即可:

@ActivityScoped
class PokemonRepository @Inject constructor(
    private val pogoApi: PogoApi
){
    suspend fun getReleasedPokemonList(): Resource<List<ReleasedPokemonModel>> {
        val response = try{
            // 直接取Map的value转为列表
            pogoApi.getReleasedPokemon().values.toList()
        } catch(e: IOException){
            return Resource.Error("请检查网络连接")
        } catch(e: HttpException){
            return Resource.Error("响应异常")
        }
        Log.d("MainActivity", "getReleasedPokemonList执行无异常")
        return Resource.Success(data = response)
    }
}

3. 额外检查项

确认你的POGO_API_BASE_URL配置正确,值应为https://pogoapi.net/api/v1/,末尾必须带斜杠,否则Retrofit路径拼接会出错。

可选优化

如果需要保留原有数据类结构,也可以自定义Gson反序列化适配器,将返回的Map手动映射为你需要的ListOfReleasedPokemon结构,上述修改方案更直接高效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 15:27:01