简体   繁体   中英

Error parsing json retrofit android array

I have this json.

{ 
"people":
 [
  { "id":0, "person":true },
  { "id":1, "person":true }
 ] 
}

Model

class Person(var id: Int, var person: Boolean)

My endpoint request

@GET("/posts")
    fun getPeople(): Call<List<Person>>

And after request I have failure response and message

java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $

The issue is that you need to create a wrapper around the list itself that contains the people property.

So you should have something like

data class PeopleList(
  var people: List<Person>
)

which should then be used in your service definition like

@GET("/posts")
fun getPeople(): Call<PeopleList>

The reason for this is that retrofit is expects a JSON list [...] , but the data being sent is a JSON object {...} that contains a list. So you need to tell retrofit how to get to the list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM