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

如何编写带依赖的自定义Kotlin序列化器并配置SerializationModule?

可以实现,具体步骤如下

你的自定义ThingSerializer因为依赖ThingRepository,无法通过注解自动注册,但完全可以手动创建实例并配置到SerializationModule中,步骤如下:

1. 创建序列化器实例

先初始化你的仓库实现,再传入序列化器构造函数:

// 假设你的仓库实现类是ThingRepositoryImpl
val thingRepository = ThingRepositoryImpl()
val thingSerializer = ThingSerializer(thingRepository)

2. 注册到SerializationModule

使用SerializersModule.Builder将序列化器与Thing类绑定:

val customSerializersModule = SerializersModule {
    // 两种注册方式任选其一
    contextual(Thing::class, thingSerializer)
    // 或者 addSerializer(Thing::class, thingSerializer)
}

3. 配置序列化工具(以Json为例)

将自定义模块传入序列化器的配置中:

val json = Json {
    serializersModule = customSerializersModule
}

验证使用

序列化示例

val testThing = Thing(id = "t1001", name = "测试物品")
val serializedJson = json.encodeToString(testThing)
// 输出结果为字符串:"t1001"

反序列化示例

val deserializedThing = json.decodeFromString<Thing>(serializedJson)
// 会通过thingRepository.findById("t1001")加载完整对象

注意事项

  • 注意线程安全:如果序列化器会被多线程调用,确保ThingRepository是线程安全的实现。
  • 空值处理:你的反序列化代码中用了!!强制非空,建议添加空值判断,比如抛出自定义异常或返回默认对象,避免空指针崩溃:
    override fun deserialize(decoder: Decoder): Thing {
        val id = decoder.decodeString()
        return thingRepository.findById(id) ?: throw IllegalArgumentException("Thing with id $id not found")
    }
    
  • 依赖注入场景:如果用Spring、Hilt等框架,可以将ThingSerializer声明为单例Bean,注入ThingRepository后再注册到SerializationModule。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 09:57:41