Kotlin deserialization error on json array, using kotlin 1.4.32

When I call a web service I get a response like this:

[{"courseId":"ACC-211","title":"Financial Accounting","creditHours":3,"department":"Accounting","titleIdSeq":"30202288","courseDescription":"Develops ... financing.","level":"L","prereqs":null},{"courseId":"ACC-212","title":"Managerial Accounting (Course)","creditHours":3,"department":"Accounting","titleIdSeq":"30202291","courseDescription":"You will be able to think on your feet and address real-world business issues.","level":"L","prereqs":"ACC 211 Financial Accounting"},{"courseId":"ACC-314","title":"Intermediate Accounting I,...}]

So an array of objects.

So I have this:

@Serializable
data class CourseCatalog(val courses:List<Course>)

@Serializable
data class CourseSession(val titleIdSeq: String,
val sectionId: String,
val format:String,
val term: String,
val duration: Int,
val startDate: String,
val endDate: String)

suspend fun fetchCourseCatalog() = client.get<CourseCatalog>("$baseUrl/courses")

And I got this error;

kotlinx.serialization.json.internal.JsonDecodingException: Unexpected JSON token at offset 0: Expected '{, kind: CLASS'
JSON input: [{"courseId":"ACC-211","title".....
    at kotlinx.serialization.json.internal.JsonExceptionsKt.JsonDecodingException(JsonExceptions.kt:24)
    at kotlinx.serialization.json.internal.JsonExceptionsKt.JsonDecodingException(JsonExceptions.kt:32)
    at kotlinx.serialization.json.internal.JsonReader.fail(JsonReader.kt:338)
    at kotlinx.serialization.json.internal.StreamingJsonDecoder.beginStructure(StreamingJsonDecoder.kt:38)
    at com.blackfox.excelsiorcollege.remote.CourseCatalog$$serializer.deserialize(Unknown Source:7)

How can I parse this json? I am using Kotlin Multiplatform.

1 Like

It needs to be client.get<Array<CourseSession>> I think. Or alternatively you could manually add the braces and a "courses": to the string

1 Like

Thanks, the first suggestion is what I used.

1 Like