You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Ktor遇序列化异常:找不到YouTubeResponse序列化器

解决Kotlinx Serialization "Serializer for class 'YouTubeResponse' is not found" 异常

错误信息

kotlinx.serialization.SerializationException: Serializer for class 'YouTubeResponse' is not found.
Please ensure that class is marked as '@Serializable' and that the serialization compiler plugin is applied.

排查与解决方案

1. 确保Kotlin版本与序列化插件版本完全匹配

序列化插件版本必须和项目使用的Kotlin编译器版本一致,否则会导致序列化代码生成失败。

  • 打开项目根目录的build.gradle(或settings.gradle.kts),确认ext.kotlin_version和序列化插件版本一致:
// 根build.gradle
ext.kotlin_version = "1.6.10"

// app模块build.gradle
plugins {
    id 'com.android.application'
    id 'kotlin-android'
    id "org.jetbrains.kotlin.plugin.serialization" version "1.6.10" // 版本需与Kotlin版本完全一致
}

2. 补充缺失的序列化依赖

检查app模块的build.gradle,确保添加了Ktor与Kotlinx序列化的必要依赖:

dependencies {
    // Ktor内容协商与序列化
    implementation "io.ktor:ktor-client-content-negotiation:$ktor_version"
    implementation "io.ktor:ktor-serialization-kotlinx-json:$ktor_version"
    // Kotlinx序列化核心库
    implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.3" // 版本需与Kotlin 1.6.10兼容
}

注意:$ktor_version替换为你项目实际使用的Ktor版本(如2.1.0)。

3. 正确配置ContentNegotiation的Json序列化器

确保Ktor HttpClient的ContentNegotiation明确使用Kotlinx Json,避免默认配置冲突:

private fun createHttpClient(): HttpClient = HttpClient {
    // ...其他配置
    install(ContentNegotiation) {
        json(Json {
            ignoreUnknownKeys = true // 可选,忽略JSON中未定义字段,避免解析失败
            isLenient = true
            prettyPrint = false
        })
    }
    // ...其他配置
}

4. 清理并重建项目

Gradle缓存或编译残留可能导致序列化代码未正确生成,执行以下操作:

  • 点击Android Studio菜单栏 Build -> Clean Project
  • 完成后点击 Build -> Rebuild Project
  • 可选:删除.gradle和build目录后重新同步项目

5. 排查父类Response的影响

YouTubeResponse继承了Response接口,暂时去掉继承关系测试是否能正常序列化,排除接口带来的兼容性问题。若去掉后恢复正常,需检查Response接口是否存在序列化相关的冲突配置。

内容的提问来源于stack exchange,提问作者VIN

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 09:33:21