在Kotlin多平台中解析JSON:io.ktor.serialization.JsonConvertException:非法输入

bkhjykvo  于 2023-04-21  发布在  Kotlin
关注(0)|答案(1)|浏览(232)

我第一次看到Kotlin多平台,并在这里遵循指南
https://kotlinlang.org/docs/multiplatform-mobile-upgrade-app.html
我有课

@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?,
)

我示例化一个HTTPClient并调用SpaceXURL,如指南中所述

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} 🚀"
    }

当我运行它并捕获异常时
kotlinx.serialization.json.internal.JsonDecodingException:应为类kotlinx.serialization.json.JsonObject(Kotlin反射不可用)作为kotlinx.serialization.Polymorphic的序列化主体,但具有类kotlinx.serialization.json.JsonArray(Kotlin反射不可用)
我已经仔细检查过了,我正在正确地遵循指南,饲料工作

插件

Kotlin(“plugin.serialization”)版本“1.8.10”

家属

实现(“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”)

7y4bm7vi

7y4bm7vi1#

解决办法是

**id(“kotlinx-serialization”)**例如

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

我发现这很奇怪,因为它被添加到了项目级别一,如下所示。

Kotlin(“plugin.serialization”)版本“1.8.10”

相关问题