首页 > 解决方案 > 改造 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

标签: kotlinretrofit2

解决方案


将您的数据类新闻更改为来自服务器的相关响应,将 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*/

}

推荐阅读