java - RETROFIT 应为 BEGIN_ARRAY,但在第 1 行第 2 列路径 $ KOTLIN 处为 BEGIN_OBJECT
问题描述
嘿伙计们,我正在尝试从 API 获取数据。我可以使用这个https://raw.githubusercontent.com/atilsamancioglu/K21-JSONDataSet/master/crypto.json json 文件,但我不能让它工作。https://www.episodate.com/api/most-popular?page=1
这是我的主要活动
private fun loadData(){
val retrofit = Retrofit.Builder()
.baseUrl("https://www.episodate.com/")
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(MovieAPI::class.java)
CoroutineScope(Dispatchers.IO).launch {
val response = retrofit.getData()
if (response.isSuccessful){
response.body()?.let {
Moviemodel = ArrayList(it)
}
}
println(Moviemodel)
}
我的数据类
data class MovieModel(
val name: String
)
和 API 类
interface MovieAPI {
@GET("api/most-popular?page=1")
suspend fun getData(): Response<ArrayList<MovieModel>>
当我尝试 https://raw.githubusercontent.com/atilsamancioglu/K21-JSONDataSet/master/crypto.json这个文件时,我可以获取数据但是每当我尝试这个https://www.episodate.com/api/most-popular ?page=1应用程序崩溃。请看一下谢谢。
解决方案
如何使用 Retrofit 和 Gson 解析嵌套列表? 这是一个类似的问题。你的模型应该像
data class Movie(
val page: Int,
val pages: Int,
val total: String,
val tv_shows: List<TvShow>
)
data class TvShow(
val country: String,
val end_date: Any,
val id: Int,
val image_thumbnail_path: String,
val name: String,
val network: String,
val permalink: String,
val start_date: String,
val status: String
)
然后API类
interface MovieAPI {
@GET("api/most-popular?page=1")
suspend fun getData(): Response<Movie>//instead of Response<ArrayList<Movie>>
在活动中
CoroutineScope(Dispatchers.IO).launch {
val response = retrofit.getData()
if (response.isSuccessful){
response.body()?.let {
shows = List(it.tv_shows)
}
}
for(show in shows){
println(show.name) // here are the names
}
}
如果你想为你的模型使用不同的属性名,你应该用@SerializedName()
. 更多信息请参考Gson:@Expose vs @SerializedName
推荐阅读
- r - 如何在 R igraph 中连接有向子图
- java - 将单选按钮值发送到 Controller Spring
- javascript - 如何让我的 ScrollView 与 React Native 中的 Scrollbar Custom Indicator 同步移动?
- node.js - 当后端和前端位于不同的仓库时,如何使用 Cypress.io 进行 E2E 测试?
- c# - C#/WPF 检索文本框输入并将其作为函数的参数传递
- c++ - 在 TEdit 上输出的按钮
- node.js - Puppeteer 在 Rendertron 中使用时会在 /tmp 中创建大量缓存文件
- python - 'if' 函数期间的'name [x] not defined'
- javascript - 无法在音频流上设置 currentTime (socket-io-stream)
- sql - 如何根据 SQL 中的自定义日期范围为会计年度创建新列?