0

I was trying to get list of students from the following json using Retrofit2

{
   "students":[
      {
         "address":{
            "city":"DETROIT",
            "state":"MI",
            "street":"4904  Yorkshire Circle",
            "zip":"48228"
         },
         "school":"A B C D School",
         "name":"Mani Nezhad"
      },
      {
         "address":{
            "city":"RED HOOK",
            "state":"NY",
            "street":"1641  Custer Street",
            "zip":"12571"
         },
         "school":"X Y Z School",
         "name":"Jane Lindberg"
      }
   ]
}

Here is my Model Class

data class Student(
    val name: String,
    val school: String,
    val address: Address
) {
    data class Address(val street: String, val city: String, val state: String, val zip: String)

And here is the method written in Interface:

    @GET("abcd")
    fun getStudents(@Query("token") token: String): Call<List<Student>>

but whenever I run the app I get this error

Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

I understand that I was trying to getch array from a json which starts with { curly bracket. Now my question is how can I fetch this student array from this type of json which starts with the curly bracket?

1
  • 1
    you have to create a a new class (for example: StudentsList) with object of List<Student> and then instead of Call<List<Student>> use Call<StudentsList> Commented Dec 3, 2020 at 6:15

1 Answer 1

3

Your response is object not Array . So you should create Wrapper Object which will hold the List<Student> . Something like this .

    data class ApiResponse(val students: List<Student>)


@GET("abcd")
fun getStudents(@Query("token") token: String): Call<ApiResponse>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.