改造Kotlin预期使用begin_object,但使用begin_array

时间:2019-12-23 13:35:43

标签: kotlin retrofit2

主要活动

   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

1 个答案:

答案 0 :(得分:0)

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

}