【问题标题】:Retrofit kotlin expected begin_object but was begin_array改造 kotlin 预期 begin_object 但是 begin_array
【发布时间】:2019-12-23 13:35:43
【问题描述】:

主要活动

   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

【问题讨论】:

标签: kotlin retrofit2


【解决方案1】:

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

}

【讨论】:

  • 我使用转换 json2kotlin 得到了这个,但我应该怎么做呢? val json = getJson() // 你的 json 值在这里 val topic = Gson().fromJson(json, Json4Kotlin_Base::class.java)
  • 您可以通过此链接jsonschema2pojo.org 将 json 转换为 pojo,然后使用代码将 Kotlin 类转换为 java -> 将 Java 文件转换为 Kotlin 文件或 CTRL + ALT + SHIFT + K
  • 我使用它,但仍然给我同样的错误 begin object 但是是 begin array
  • 你能告诉我从服务器返回的结果吗?因为我正在尝试检查结果是否为有效的 json 格式
  • { "items": [ { "title": "", "pubDate": "", "link": "", "guid": "", "author": "", “描述”:“”,“内容”:“”,“附件”:{“链接”:“”,“类型”:“”},“类别”:[“”]}}
猜你喜欢
  • 2020-02-10
  • 2021-01-27
  • 2020-07-26
  • 2015-07-24
  • 1970-01-01
  • 2020-03-14
  • 1970-01-01
  • 2014-08-01
  • 2015-11-26
相关资源
最近更新 更多