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

Kotlin Ktor序列化JSON报错:缺失类鉴别器致多态序列化器未找到

问题:Ktor解析JSON为Map<String, MenuCategory>时崩溃

JSON响应内容

{"Appetizers": {"menu": ["Spinach Artichoke Dip","Hummus","Fried Calamari Rings","Fried Mushrooms"]},"Salads": {"menu": ["Greek","Caesar","Mediterranean Tuna Salad","Grilled Chicken Salad"]},"Drinks": {"menu": ["Water","Coke","Beer","Iced Tea"]},"Dessert": {"menu": ["Baklawa","Ice cream"]}}

客户端配置代码

private val client = HttpClient(Android) {
    install(ContentNegotiation) {
        json(
            contentType = ContentType("text", "plain"))
    }
}

触发崩溃的代码

@Serializable
class MenuCategory(
    val menu: List<String>
)

val response: Map<String, MenuCategory> =
    client.get("https://raw.githubusercontent.com/Meta-Mobile-Developer-PC/Working-With-Data-API/main/littleLemonMenu.json")
        .body()

错误信息

io.ktor.serialization.JsonConvertException: Illegal input
Caused by: kotlinx.serialization.json.internal.JsonDecodingException: Polymorphic serializer was not found for missing class discriminator ('null')
JSON input: .....er","Iced Tea"]},"Dessert":{"menu":["Baklawa","Ice cream"]}}

修复方案

错误根源是Ktor默认的Json序列化器误将Map<String, MenuCategory>中的MenuCategory当作多态类型,期望存在类鉴别符字段,但实际JSON中并没有该字段,导致解析失败。可以通过以下步骤修复:

  1. 调整Json序列化器配置
    修改HttpClient的ContentNegotiation配置,显式配置Json序列化参数,关闭多态相关检查并开启宽松解析:
private val client = HttpClient(Android) {
    install(ContentNegotiation) {
        json(Json {
            ignoreUnknownKeys = true // 忽略JSON中未知字段,避免解析失败
            isLenient = true // 启用宽松解析规则
            polymorphicIgnoreUnknownSubtypes = true // 关闭多态子类型检查
        }, contentType = ContentType("text", "plain"))
    }
}
  1. 明确指定解析类型(可选)
    虽然原代码已声明变量类型,仍可显式在body()方法中指定类型,提升解析的明确性:
val response = client.get(url)
    .body<Map<String, MenuCategory>>()
  1. 确认序列化注解有效性
    确保MenuCategory类的@Serializable注解来自kotlinx.serialization.Serializable包,避免导入错误导致的序列化失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 18:17:37