Reputation: 5
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?
Upvotes: 0
Views: 890
Reputation: 1105
Your API is returning Array of Strings, but you are fetching array of Domain Objects.
Change:
Call<List<Domain>>
to
Call<List<String>>
will work.
Upvotes: 0
Reputation: 1151
Change
fun getAllDomains(): Call<List<Domain>>
to
fun getAllDomains(): Call<List<String>>
because api return list of strings not objects https://i.sstatic.net/wlUEB.jpg
Upvotes: 1