【发布时间】:2021-01-27 06:58:15
【问题描述】:
我试图创建一个应用程序,其本质是通过按一个按钮,显示我的api中的作者和标题,但是它给出了一个错误预期的begin_array但在第1行是begin_object,我尝试了一切,没有有效,有什么问题
MainActivity.kt:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
btn.setOnClickListener {
sendNetworkRequest()
}
}
fun sendNetworkRequest(){
val builder = Retrofit.Builder()
.baseUrl("http://newsapi.org/v2/")
.addConverterFactory(GsonConverterFactory.create())
val retrofit = builder.build()
val apiInterface: ApiInterface = retrofit.create<ApiInterface>(ApiInterface::class.java)
val call: retrofit2.Call<UrlImageModel> = apiInterface.getFile()
call.enqueue(object : Callback<UrlImageModel>{
override fun onFailure(call: retrofit2.Call<UrlImageModel>, t: Throwable) {
Log.i("LOL",t.message.toString())
}
override fun onResponse(call: retrofit2.Call<UrlImageModel>, response: Response<UrlImageModel>) {
val statusResponse = response.body()!!
result.text = result.text.toString() + '\n' + statusResponse.status
}
})
}
ApiInterface.kt:
interface ApiInterface {
@GET("everything?q=bitcoin&from=2020-09-12&sortBy=publishedAt&apiKey=1d4f4f812b0b458890db5757fa0d8ce0")
fun getFile(): Call<UrlImageModel>
}
UrlImageModel.kt
class UrlImageModel {
@SerializedName("status")
@Expose
var status: String? = null
@SerializedName("totalResults")
@Expose
var totalResult: String? = null
@SerializedName("articles")
@Expose
var articles = ArrayList<Articles>()
}
class Articles{
@Expose
@SerializedName("source")
var source = ArrayList<Source>()
@SerializedName("author")
@Expose
var author: String? = null
@SerializedName("title")
@Expose
var title: String? = null
@SerializedName("description")
@Expose
var description: String? = null
@SerializedName("url")
@Expose
var url: String? = null
@SerializedName("urlToImage")
@Expose
var urlToImage: String? = null
@SerializedName("publishedAt")
@Expose
var publishedAt: String? = null
@SerializedName("content")
@Expose
var content: String? = null
}
class Source{
@SerializedName("id")
@Expose
var id: String? = null
@SerializedName("name")
@Expose
var name: String? = null
}
来自我的 API 的 JSON(不是全部) enter image description here
【问题讨论】:
标签: android arrays api kotlin retrofit