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

Kotlin复杂自定义类型序列化报错求助:Pair与ItemStack序列化失败

Kotlin Serialization 复杂类型序列化问题

我在尝试序列化自定义数据类型,简单类型(比如UUID)用官方文档的方法能正常工作,但处理复杂类型时碰到了问题。

对象类代码

@Serializable(with = PairSerializer::class) //此处报错
private val equipment = mutableListOf<Pair<ItemSlot, ItemStack>>()

序列化器类代码

class PairSerializer() : KSerializer<Pair<EnumWrappers.ItemSlot, ItemStack>> {
    override val descriptor: SerialDescriptor = buildClassSerialDescriptor("PairEnumISSerializer") {
    }

    override fun serialize(encoder: Encoder, value: Pair<EnumWrappers.ItemSlot, ItemStack>) {
    //实现代码
    }

    override fun deserialize(decoder: Decoder): Pair<EnumWrappers.ItemSlot, ItemStack> {
    //实现代码
    }
}

报错信息

Serializer has not been found for type 'Pair<EnumWrappers.ItemSlot, ItemStack>'. To use context serializer as fallback, explicitly annotate type or property with @Contextual

我没法在序列化器类上方添加@Serializer(forClass = Pair<EnumWrappers.ItemSlot, ItemStack>::class),会报错:"Only classes are allowed on the left hand side of a class literal",网上也没找到解决办法。

已尝试的无效方法

  • 在需要序列化的属性上方添加@Serializable注解;
  • 单独序列化每个类型;
  • 参照UUID序列化器的写法,在序列化器类上方添加@Serializer注解;
  • 改用Map替代Pair的可变列表,同时为ItemStack编写新序列化器,但仍出现类似报错:
    Serializer has not been found for type 'ItemStack'. To use context serializer as fallback,  explicitly annotate type or property with @Contextual
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 03:16:14