0

Hi I am currently developing an android studio application with kotlin and receiving this issue when attempting a GET request . As below are my code stubs . Any help would be appreciated I am new to this language.

data class Post (

    val id: Int,
    val username: String,
    val password: String,
    val created_at: String,
    val updated_at: String

)

class courseViewModelFactory(private val repository: Repository): ViewModelProvider.Factory { override fun <T : ViewModel?> create(modelClass: Class): T {

    return courseViewModel(repository) as T

}

class courseViewModel(private val repository: Repository): ViewModel() {

val myResponse: MutableLiveData<Response<Post>> = MutableLiveData()
fun getPost(){
    viewModelScope.launch {

        val response = repository.getPost()
            myResponse.value = response
    }
}

}

class Repository {

suspend fun getPost(): Response<Post> {
 return   RetrofitInstance.api.getPost()
}

}

object RetrofitInstance {

private val retrofit by lazy {

    Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .build()
}

val api: SimpleApi by lazy {

    retrofit.create(SimpleApi::class.java)
}

}

interface SimpleApi {

@GET("api/v1/users")
suspend fun getPost(): Response<Post>

}

  • That problem refers that retrofit is trying to parse an JSON Object ( Post ) but instead of that Retrofit found a Json Array ([Post]), – Juanjo Berenguer Feb 27 '21 at 23:00
  • Hi I am new to kotlin , Do i need to modify the Retroft class ? – OmalleyTomas98 Feb 27 '21 at 23:19
  • @JuanjoBerenguer , Hi I am new to kotlin , Do i need to modify the Retroft class ? – OmalleyTomas98 Feb 28 '21 at 00:00
  • You just have to check how is the json you want to process and how you defined your Post class, take a look here( related question): https://stackoverflow.com/questions/36177629/retrofit2-android-expected-begin-array-but-was-begin-object-at-line-1-column-2?rq=1 – Juanjo Berenguer Feb 28 '21 at 10:45

0 Answers0