【问题标题】:Expected BEGIN_OBJECT but was string at path $[0]预期为 BEGIN_OBJECT,但在路径 $[0] 处是字符串
【发布时间】:2021-06-09 11:00:41
【问题描述】:

JSON

我尝试从链接中解析 JSON。这是我的代码

private const val BASE_URL = "https://raw.githubusercontent.com/"

private val moshi = Moshi.Builder()
    .add(KotlinJsonAdapterFactory())
    .build()

private val retrofit = Retrofit.Builder()
    .addConverterFactory(MoshiConverterFactory.create(moshi))
    .baseUrl(RetrofitUtil.BASE_URL)
    .build()

interface DomainsApiService {
    @GET("Maximsiomin/DomainsAPI/master/domains_list.json")
    fun getAllDomains(): Call<List<Domain>>
}

object DomainsAPI {
    val retrofitService: DomainsApiService by lazy { retrofit.create(DomainsApiService::class.java) }
}

data class Domain(
    @Json(name = JSON.DOMAIN) val domain: String
)

我在这里处理 JSON:

fun getDomainsList(domain: String, context: Context) {
    DomainsAPI.retrofitService.getAllDomains().enqueue( object: Callback<List<Domain>> {
        override fun onFailure(call: Call<List<Domain>>, t: Throwable) {
            Timber.d("onFailure called")
            Toast.makeText(context, "Error: " + t.message, Toast.LENGTH_LONG).show()
        }

        override fun onResponse(call: Call<List<Domain>>, response: Response<List<Domain>>) {
            Timber.d("onResponse called")
            _response.value = response.body()?.size.toString()
        }
    })
}

但是我的 Toast 出现错误“预期 BEGIN_OBJECT 但在路径 $[0] 处是字符串”。我试图编辑 json 文件并制作了一个 dict,但得到了同样的错误。我能做什么?

【问题讨论】:

  • 您的数据是字符串数组,而不是Domain 对象数组。

标签: android kotlin retrofit2 moshi


【解决方案1】:

改变

fun getAllDomains(): Call<List<Domain>>

fun getAllDomains(): Call<List<String>>

因为 api 返回的字符串列表不是对象https://i.imgur.com/dB1lU4q.jpg

【讨论】:

    【解决方案2】:

    您的 API 正在返回字符串数组,但您正在获取域对象数组。

    变化:

      Call<List<Domain>>
    

      Call<List<String>>
    

    会起作用的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-10
      • 2020-03-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多