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

Kotlinx Serialization多态序列化:整数类型鉴别器适配方案

解决kotlinx.serialization处理整数类型多态判别器的问题

核心问题是kotlinx.serialization默认以字符串作为多态判别器的匹配依据,而你的JSON中使用整数类型的type字段。不需要提前修改JSON,直接通过自定义判别器映射即可解决:

1. 定义多态类层级

先声明基类和子类,确保都添加@Serializable注解:

import kotlinx.serialization.*

@Serializable
sealed class Item {
    abstract val id: String
}

@Serializable
data class TextItem(override val id: String, val text: String) : Item()

@Serializable
data class NumberItem(override val id: String, val number: Int) : Item()

2. 配置Json序列化器

创建Json实例时,在polymorphic块中为每个子类绑定对应的整数判别器,同时指定判别器字段为type(默认字段名就是type,如果是其他字段可手动指定):

import kotlinx.serialization.json.Json

val json = Json {
    polymorphic(Item::class) {
        // 绑定子类与整数判别器
        subclass(TextItem::class, 0)
        subclass(NumberItem::class, 1)
        // 可选:添加默认子类处理未知type
        // defaultSubclass(UnknownItem::class)
    }
    ignoreUnknownKeys = true // 可选,忽略JSON中未知字段避免报错
}

3. 序列化与反序列化示例

反序列化

假设你的JSON结构如下:

{
  "items": [
    {"type": 0, "id": "1", "text": "测试文本"},
    {"type": 1, "id": "2", "number": 66}
  ]
}

先定义根实体类:

@Serializable
data class ItemList(val items: List<Item>)

执行反序列化:

val jsonString = """{"items": [{"type": 0, "id": "1", "text": "测试文本"}, {"type": 1, "id": "2", "number": 66}]}"""
val itemList = json.decodeFromString<ItemList>(jsonString)

序列化

生成符合格式的JSON:

val items = listOf(
    TextItem("3", "新文本"),
    NumberItem("4", 99)
)
val serializedJson = json.encodeToString(ItemList(items))

关键说明

  • 不需要提前转换JSON中的type字段值,配置后的序列化器会直接识别整数判别器
  • 如果基类不是密封类,只需在polymorphic块中注册所有子类即可
  • 若判别器字段名不是type,可在polymorphic块中添加discriminator = "自定义字段名"指定

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 06:16:18