Search code examples
androidkotlinretrofit2moshi

Expected BEGIN_OBJECT but was string at path $[0]


JSON

I try to parse JSON from the link. Here's my code

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
)

Here i process 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()
        }
    })
}

But I have Toast with error "Expected BEGIN_OBJECT but was string at path $[0]". I tried to edit json file and made a dict, but got same error. What can I do?


Solution

  • Your API is returning Array of Strings, but you are fetching array of Domain Objects.

    enter image description here

    Change:

      Call<List<Domain>>
    

    to

      Call<List<String>>
    

    will work.