【问题标题】:Error with Retrofit and moshi while parsing json解析 json 时 Retrofit 和 moshi 出错
【发布时间】:2020-02-10 01:28:48
【问题描述】:

我使用 Kotlin,并且我想使用改造来使用 imgur 的 API,但是当我发送请求并收到答复时出现此错误:

“E/Retrofit:应为 BEGIN_ARRAY,但在路径 $ 处为 BEGIN_OBJECT”

所以,这就是我收到的:

{"data":["TY5OVQo"],"success":true,"status":200}

由此,我有了这个数据类:

@JsonClass(generateAdapter = true)
data class ImgurBasic<T>(@Json(name = "data") val data: T,
                         @Json(name = "success") val success: Boolean,
                         @Json(name = "status") val status: Int)

我在调用改造时使用这个接口:

interface Imgur {
    @GET("3/account/{username}/images/ids")
    fun getImages(@Path("username") username: String): Call<List<ImgurBasic<List<String>>>>
}

以及我如何使用改造和 moshi:

val header = StringBuilder("Bearer ").append(AuthSettings.data!!.accessToken!!).toString()
val client = OkHttpClient.Builder()
client.addInterceptor { chain ->
    val original = chain.request()
    val requestBuilder = original.newBuilder()
        .header("Authorization", header)

    val request = requestBuilder.build()
    chain.proceed(request)
}
val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
val service = Retrofit.Builder()
    .baseUrl(baseUrl)
    .client(client.build())
    .addConverterFactory(MoshiConverterFactory.create(moshi))
    .build()
    .create(Imgur::class.java)
    .getImages(AuthSettings.data!!.accountUsername!!)
    .enqueue(object : Callback<List<ImgurBasic<List<String>>>> {
        override fun onResponse(call: Call<List<ImgurBasic<List<String>>>>, response: Response<List<ImgurBasic<List<String>>>>) {
            val body = response.body()
            Log.d("Retrofit", response.message())
            Log.d("Retrofit", if (response.isSuccessful) "true" else "false")

            if (body != null) {
                // Parse data
            }
        }

        override fun onFailure(call: Call<List<ImgurBasic<List<String>>>>, t: Throwable) {
            Log.e("Retrofit", t.message) // Error Here
        }
    })

在我的dataClass中我放了一个模板,因为数据可能是不同的类型

提前致谢

PS:对不起我的英语^^

【问题讨论】:

    标签: android android-studio kotlin retrofit retrofit2


    【解决方案1】:

    好吧我终于找到答案了,我只是看错地方了:

    Call<List<ImgurBasic<List<String>>>>
    

    必须是:

    Call<ImgurBasic<List<String>>>
    

    我专注于 ImgurBasic 的内容。

    【讨论】:

      猜你喜欢
      • 2021-04-24
      • 2018-07-15
      • 2018-12-25
      • 2018-07-26
      • 2021-02-03
      • 1970-01-01
      • 2014-10-19
      • 2016-08-06
      • 1970-01-01
      相关资源
      最近更新 更多