Reputation: 119
I am getting data from a json api in my Kotlin code. I can parse the data correctly for string values but parsing the list of arrays is causing issues.
My response data is follows
{
"limit": "10",
"schedule": {
"0": ["0", "3.00", "7.59", "9.00", "12.59", "14.00", "22.59"],
"1": ["1", "3.00", "7.59", "9.00", "12.59", "14.00", "22.59"],
"2": ["2", "3.00", "7.59", "9.00", "12.59", "14.00", "22.59"],
"3": ["3", "3.00", "7.59", "9.00", "12.59", "14.00", "22.59"],
"4": ["4", "3.00", "7.59", "9.00", "12.59", "14.00", "22.59"],
"5": ["5", "3.00", "7.59", "9.00", "12.59", "14.00", "22.59"],
"6": ["6", "3.00", "7.59", "9.00", "12.59", "14.00", "22.59"]
},
"target_temp": "32.18"
}
Now to retrieve the value e.g target_temp I am using following code successfully
val gson = GsonBuilder().create()
val target = gson.fromJson(body, data::class.java) println(target.target_temp)
and my class code is simple
class data(val target_temp: String)
Now when I want to access the schedule I get the error.
java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 50 path $.schedule
My code to retrieve schedule is below.
val gson = GsonBuilder().create()
val schedule = gson.fromJson(body, schedule::class.java)
println(schedule.schedule.get(1))
and class for schedule is
class schedule(val schedule: ArrayList<String>)
Upvotes: 0
Views: 147
Reputation: 5300
Schedule is not of type ArrayList<String
put of type Map<ArrayList<String>>
.
Change your definition of schedule to:
class schedule(val schedule: Map<String, ArrayList<String>>)
Full example:
val gson = GsonBuilder().create()
val schedule = gson.fromJson(body, schedule::class.java)
println(schedule.schedule.get("0"))
Upvotes: 1
Reputation: 577
in your response model set schedule
variable datatype Map<String, List<String>>
instead of Schedule
class object
or List<String>
your response model will look like below
data class ResponseModel(
val schedule: Map<String, List<String>>,
val target_temp: String
)
Upvotes: 1