我需要在反序列化期间向类构造函数注入局部值。例如,看下面的课。
@Serializable
class Someclass(val local: Context,val serialized: String)
我希望在序列化过程中跳过字段local
,并在反序列化过程中将其替换为一些预定义的本地值。
背后的原因是我将通过网络传输模型,但是对这些模型的操作依赖于要注入的本地上下文。
因为我没有找到实现它的任何标准方法,所以我决定使用上下文序列化。所以我写了序列化器:
class ContextualInjectorSerializer<T>(private val localValue: T) : KSerializer<T> {
override val descriptor = SerialDescriptor("ValueInjection",StructureKind.OBJECT)
override fun deserialize(decoder: Decoder): T {
decoder.beginStructure(descriptor).endStructure(descriptor)
return localValue
}
override fun serialize(encoder: Encoder,value: T) {
encoder.beginStructure(descriptor).endStructure(descriptor)
}
}
并以这种方式使用它:
// Context is marked with @Serializable(with = ContextSerializer::class)
val json = Json(Jsonconfiguration.Stable,SerializersModule {
contextual(Context::class,ContextualInjectorSerializer(context))
})
// serialize/deserialize
令人惊讶的是,它在JVM上运行良好。但是,当我将其编译为JS并进行测试时,我得到了TypeError: Cannot read property 'siteId' of undefined
。这里的siteId
是我尝试访问的上下文字段。
是否有注入本地参数的标准方法?我的把戏怎么了?