Search code examples
androidkotlinretrofitlogcat

Making news application using retrofit, D/json: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $


i'm trying to catch some data from some API and i was using Toast to make sure if there's a response or not, and i keep getting this error:- D/json: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $

Thanks in advance :)

Here is my Retrofit interface

import retrofit2.Call
import retrofit2.http.GET

interface CallableInterface {

    @GET("/api/v1/dev_tracker?page=1&source=reddit")
    fun getNews(): Call<News>
}

And News Class that i've called in the interface


import com.google.gson.annotations.SerializedName
import java.nio.file.Files.size

class News {

    val dev_posts: Array<Article> = arrayOf(Article())



}

class Article {

    var content: String = ""

    var language: String = ""

    var title: String = ""

}

and here is my activity

fun loadNews() {
        val progress: ProgressBar = findViewById(R.id.pb)
        val retrofit = Retrofit
            .Builder()
            .baseUrl("https://newworldfans.com")
            .addConverterFactory(GsonConverterFactory.create())
            .build()

        val callable = retrofit.create(CallableInterface::class.java)
        val getNews = callable.getNews()
        getNews.enqueue(object : Callback<News> {
            override fun onResponse(call: Call<News>, response: Response<News>) {
                progress.visibility = View.GONE
                val news: News? = response.body()
                Toast.makeText(this@DrawerActivity,
                   "${news?.dev_posts?.get(0)?.content} ", Toast.LENGTH_SHORT).show();
                Log.d("jsoon", "Success"  )
            }

            override fun onFailure(call: Call<News>, t: Throwable) {
                progress.visibility = View.GONE
                Toast.makeText(this@DrawerActivity, "Failed", Toast.LENGTH_SHORT).show();
                Log.d("json", "${t.localizedMessage} ")
            }
        })

Solution

  • Your API returns the articles directly as an array instead of wrapping it in an object.

    You can use: fun getNews(): Call<List<Article>>