我正在尝试kotlinx.serialization
为Compose Desktop
类创建一个序列化程序,我有这个:
@Serializer(forClass = MutableState::class)
class MutableStateSerializer<T>(private val dataSerializer: KSerializer<T>) : KSerializer<MutableState<T>> {
override fun deserialize(decoder: Decoder) = mutableStateOf(decoder.decodeSerializableValue(dataSerializer))
override val descriptor: SerialDescriptor = dataSerializer.descriptor
override fun serialize(encoder: Encoder, value: MutableState<T>) = encoder.encodeSerializableValue(dataSerializer, value.value)
}
这应该用于MutableState
类的实例(如@Serializer
注释所述),但我必须为每个属性放置一个显式序列化程序,否则我会收到此错误:
xception in thread "main" kotlinx.serialization.SerializationException: Class 'SnapshotMutableStateImpl' is not registered for polymorphic serialization in the scope of 'MutableState'.
Mark the base class as 'sealed' or register the serializer explicitly
使用的代码:
@Serializable
class Test {
var number = mutableStateOf(0)
}
fun main() {
val json = Json { prettyPrint = true }
val serialized = json.encodeToString(Test())
println(serialized)
}
我必须将此注释放在我的财产上:
@Serializable(with = MutableStateSerializer::class)
没有办法自动将我的序列化程序链接到MutableState
接口吗?由于SnapshotMutableStateImpl
是内部的,我无法将其设置为此类。