Search code examples
androidjsonkotlingsonjson-deserialization

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


I'm trying to parse the following json using Google's Gson with Kotlin on android

{
    "status": 0,
    "msg": null,
    "data": {
        "timeTables": [
            {
                "type": "timetable",
                "startTime": "2021-12-13 11:00:00",
                "endTime": "2021-12-13 13:00:00",
                "location": "XXXX",
                "moduleCode": "XXXX",
                "staffName": "XXXX"
            },
            {
                "type": "timetable",
                "startTime": "2021-12-13 14:00:00",
                "endTime": "2021-12-13 16:00:00",
                "location": "XXXX",
                "moduleCode": "XXXX",
                "staffName": "XXXX"
            },
            {
                "type": "timetable",
                "startTime": "2021-12-13 16:00:00",
                "endTime": "2021-12-13 18:00:00",
                "location": "XXXX",
                "moduleCode": "XXXX",
                "staffName": "XXXX"
            }
        ]
    },
    "success": true
}

the model and code I use are displayed below:

import com.google.gson.annotations.SerializedName

class TimeTableModel {
    @SerializedName("status")
    val status = 0

    @SerializedName("message", alternate = ["msg"])
    val message : String? = ""

    @SerializedName("success")
    val success = false

    @SerializedName("data")
    val data : TimeTableData = TimeTableData()
}

class TimeTableData {
    @SerializedName("timeTables")
    val timeTables : List<TimeTableListData> = emptyList()
}

class TimeTableListData {
    @SerializedName("startTime")
    val startTime = ""

    @SerializedName("endTime")
    val endTime = ""

    @SerializedName("location")
    val location = ""

    @SerializedName("moduleCode")
    val moduleCode = ""

    @SerializedName("staffName")
    val staffName = ""
}
fun getTimetable() {
    val data = get("$baseAddress/userTimeTable/findCalendarMessage")
    return Gson().fromJson(data, TimeTableModel::class.java) // data is the json above
}

I expect it to work correctly, however an exception was raised everytime it deserialize:
Gson: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 184 path $.data

What am I doing wrong? Gson does not support list de-serialization?


Solution

  • I copied the above and it works for me. I suggest making sure that the string in data is identical to the JSON provided above.