Home > Blockchain >  Error in Kotlin (Retrofit) Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $ [SOLV
Error in Kotlin (Retrofit) Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $ [SOLV

Time:04-19

Hello guys I am pretty new in Kotlin and I am trying to implement retrofit api calls for my backend. I am getting this error in logcat: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $ Any advice is appreciated.


import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;

public interface Api {

    @GET("api/users")
    fun getUsers(): Call<List<UsersItem>>
    

}

This is my data class:

package com.example.mtaa

data class UsersItem(
    val branches: List<Any>,
    val id: Int,
    val mail: String,
    val name: String,
    val password: String,
    val preferred_branch: String,
    val profile_pic: String,
    val reservations: List<Any>,
    val sub_at: String
)

This code is in MainActivity

private fun getMyUsers() {
        val retrofitBuilder = Retrofit.Builder()
            .addConverterFactory(GsonConverterFactory.create())
            .baseUrl(BASE_URL)
            .build()
            .create(Api::class.java)
        val retrofitData = retrofitBuilder.getUsers()

        retrofitData.enqueue(object : Callback<List<UsersItem>?> {
            override fun onResponse(
                call: Call<List<UsersItem>?>,
                response: Response<List<UsersItem>?>
            ) {
                val responseBody = response.body()!!

                val myStringBuilder = StringBuilder()
                for(myData in responseBody){
                    myStringBuilder.append(myData.name)
                    myStringBuilder.append("\n")
                }

                binding.txtId.text = myStringBuilder

            }
            override fun onFailure(call: Call<List<UsersItem>?>, t: Throwable) {
                Log.d("ERROR With BE", "Error:"   t.message)
            }
        })
    }

This is JSON which I am getting from my django backend

{
"results":[
    "id": 1,
    "password": "*******",
    "name": "Name Surname",
    "mail": "[email protected]",
    "preferred_branch": "City",
    "sub_at": "2022-02-04",
    "profile_pic": "path",
    "branches": {
        "id": 1,
        "location": "City",
        "gym_capacity": X,
        "pool_capacity": X,
        "sauna_capacity": X
    },
    "reservations": []
],
...
}

CodePudding user response:

In your Retrofit service, you're saying you expect a List of items to come back, but your API is returning a single object with a list inside of it.

What you want to do instead is create a type called UserResults (or something similar) that contains a results property, which is a List<UsersItem>.

data class UserResults(
    val results: List<UsersItem>
)

Then, your Retrofit function can return this new type instead:

@GET("api/users")
fun getUsers(): Call<UserResults>
  • Related