Search code examples
jsonkotlinjetbrains-idekotlin-multiplatformktor

Parsing JSON in Kotlin Multiplatform : io.ktor.serialization.JsonConvertException: Illegal input


I am taking my first look at Kotlin Multiplatform and am following the guide here

https://kotlinlang.org/docs/multiplatform-mobile-upgrade-app.html

I have my class

@Serializable
data class RocketLaunch (
    @SerialName("flight_number")
    val flightNumber: Int,
    @SerialName("name")
    val missionName: String,
    @SerialName("date_utc")
    val launchDateUTC: String,
    @SerialName("success")
    val launchSuccess: Boolean?,
)

I instantiate a HTTPClient and call the SpaceX URL as detailed in the guide

private val httpClient = HttpClient {
        install(ContentNegotiation) {
            json(Json {
                prettyPrint = true
                isLenient = true
                ignoreUnknownKeys = true
            })
        }
    }

    @Throws(Exception::class)
    suspend fun greet(): String {
        val rockets: List<RocketLaunch> = httpClient.get("https://api.spacexdata.com/v4/launches").body()
        val lastSuccessLaunch = rockets.first() //{ it.launchSuccess == true }
        return "Guess what it is! > ${platform.name.reversed()}!"
                "\nThe last successful launch was ${lastSuccessLaunch.title} 🚀"
    }

And when I run it and catch the exception I get

kotlinx.serialization.json.internal.JsonDecodingException: Expected class kotlinx.serialization.json.JsonObject (Kotlin reflection is not available) as the serialized body of kotlinx.serialization.Polymorphic, but had class kotlinx.serialization.json.JsonArray (Kotlin reflection is not available)

I have double checked and I am following the guide properly, and the feed works

Plugin

kotlin("plugin.serialization") version "1.8.10"

Dependancies

implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4")

implementation("io.ktor:ktor-client-core:$ktorVersion")

implementation("io.ktor:ktor-client-content-negotiation:$ktorVersion")

implementation("io.ktor:ktor-serialization-kotlinx-json:$ktorVersion")


Solution

  • The fix was to add

    id("kotlinx-serialization") e.g.

    plugins {
        kotlin("multiplatform")
        id("com.android.library")
        id("kotlinx-serialization")
    }
    

    To the shared build.gradle.kts file. I find this odd as it was added to the Project level one as shown below.

    kotlin("plugin.serialization") version "1.8.10"