kotlin - 改造 kotlin 预期 begin_object 但是 begin_array
问题描述
主要活动
val retrofit = Retrofit.Builder()
.baseUrl("http://192.168.1.78:3000")
.addConverterFactory(GsonConverterFactory.create())
.build()
val api = retrofit.create(ApiService::class.java)
api.fetchLastNews().enqueue(object : Callback<List<News>>{
override fun onResponse(call: Call<List<News>>, response: Response<List<News>>) {
d("exemplo","onResponse")
}
override fun onFailure(call: Call<List<News>>, t: Throwable) {
d("exemplo","onFailure")
}
})
}
界面
interface ApiService {
@GET("/getultimas")
fun fetchLastNews(): Call<List<News>>
}
数据类
package com.example.navigationdrawer
data class News (
val titulo: String
)
来自节点 api 的响应
app.get('/getultimas', function (req, res) {
console.log("ultimas noticias");
results = transform(jsonLastNews);
res.json(results);
});
它给出错误改造 kotlin 预期的 begin_object 但是 begin_array
解决方案
将您的数据类新闻更改为来自服务器的相关响应,将 json 转换为 pojo kotlin 检查此Create POJO Class for Kotlin
编辑:
因为从服务器返回 json 是{ "items": [ { "title": "", "pubDate": "", "link": "", "guid": "", "author": "", "description": "", "content": "", "enclosure": { "link": "", "type": "" }, "categories": [ "" ] } ]}
您可以将数据类更改为
data class News {
@SerializedName("items") //this json key
@Expose
val items: List<Item>?= null; /*items is list array because response [] tag*/
}
/* class for List Item */
data class Item {
@SerializedName("title") //this key value from json
@Expose
val title:String; //this key value to variable string in kotlin the type is String
@SerializedName("pubDate")
@Expose
val pubDate:String;
@SerializedName("link")
@Expose
val link:String;
/* you can add other data*/
}
推荐阅读
- pandas - 如何在月度数据中向 Pandas 添加缺失数据
- jquery - 用 css 和 svg 绘制区块链
- windows - Powershell - 在特定时间后关闭 Out-GridView
- html - VBA在IE中单击登录按钮
- python - Numpy 3D 数组乘以 2D 数组
- angularjs - 从 Angular1 迁移到 Angular5(并行运行)
- php - 使用 cURL 和 simple_html_dom 抓取时服务器崩溃
- c# - C# 执行多个命令行时出错
- domain-driven-design - Lagom 或微服务中的异步流程设计
- python - Keras最简单的conv网络没有学到任何东西