【发布时间】:2021-10-28 01:39:59
【问题描述】:
这是我尝试使用的 API/JSON 数据:https://pogoapi.net/api/v1/pokemon_names.json
问题是当我尝试解析 JSON 响应时,只返回 null。
型号:
data class ListOfReleasedPokemon(
val releasedPokemon: List<PokemonResponse>
)
data class PokemonResponse(
val pokemonMap: Map<String, ReleasedPokemonModel>
)
data class ReleasedPokemonModel(
val id: Int,
val name: String
)
API 调用:
interface PogoApi {
@GET("released_pokemon.json")
suspend fun getReleasedPokemon(): ListOfReleasedPokemon
}
应用模块:
@Module
@InstallIn(SingletonComponent::class)
object AppModule {
@Singleton
@Provides
fun providePokemonRepository(
pogoApi: PogoApi
) = PokemonRepository(pogoApi)
@Singleton
@Provides
fun providePogoApi(): PogoApi{
// val gson = GsonBuilder()
// .registerTypeAdapter(ReleasedPokemonModel::class.java, JsonDeserializer())
// .create()
return Retrofit.Builder()
.baseUrl(POGO_API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(PogoApi::class.java)
}
}
存储库(发现错误的位置):
@ActivityScoped
class PokemonRepository @Inject constructor(
private val pogoApi: PogoApi
){
suspend fun getReleasedPokemonList(): Resource<ListOfReleasedPokemon> {
val response = try{
pogoApi.getReleasedPokemon()
// Returns null
} catch(e: IOException){
return Resource.Error("Please check your internet connection")
} catch(e: HttpException){
return Resource.Error("Unexpected response")
}
Log.d("MainActivity", "GetPokemonReleasedList Run with no errors")
return Resource.Success(data = response)
}
}
任何帮助将不胜感激!
【问题讨论】:
-
我看到API中的列表项实际上不是列表,它是一个常规对象,里面包含其他对象。也许您应该查看您的数据响应。
-
如果它是这种格式,我有办法解析它吗?
标签: android json kotlin retrofit