Search code examples
jsonkotlinretrofit

Access to Nested Json Kotlin


I don't know how to get data from nested Json

{
  
   "results":[
      {
         "id":1,
         "name":"Rick Sanchez",
         "status":"Alive",
         "species":"Human",
         "type":"",
         "gender":"Male",

Json looks like above, i want to get access to name variable. My code: Data class:

data class Movie(
    @Json(name = "results") val results: List<MovieDetail>
)
data class MovieDetail(
    @Json(name = "name") val name: String

)

ApiService:

private const val BASE_URL = "https://rickandmortyapi.com/api/"

private val moshi = Moshi.Builder()
    .add(KotlinJsonAdapterFactory())
    .build()

private val retrofit = Retrofit.Builder()
    .addConverterFactory(MoshiConverterFactory.create(moshi))
    .baseUrl(BASE_URL)
    .build()

interface MovieApiService {
    @GET("character")
    suspend fun getMovies(): List<Movie>
}

object MovieApi {
    val retrofitService : MovieApiService by lazy {
        retrofit.create(MovieApiService::class.java)
    }
}

And ViewModel:

  private val _status = MutableLiveData<String>()
    val status: LiveData<String> = _status

    init {
        getMovies()
    }

    private fun getMovies() {
        viewModelScope.launch {
            val listResult = MovieApi.retrofitService.getMovies()
            _status.value = "Success: ${listResult.size} names retrieved"
        }
    }

For plain Json there is no problem but i don't know how to get access to this nested variables, i think that i have to use "results" variable from data class but i don't know where and how. During running app i've got error: Expected BEGIN_ARRAY but was BEGIN_OBJECT at path $


Solution

  • You should change

    @GET("character")
    suspend fun getMovies(): List<Movie>
    

    To:

    @GET("character")
    suspend fun getMovies(): Movie
    

    You are receiving object and not list of objects