[英]How can I encode a typed class with Kotlinx Serialization?
I'd like to encode a given class of type T: EventData
with Kotlinx Serialization encodeToString
.我想使用 Kotlinx Serialization
encodeToString
对给定的类型T: EventData
进行encodeToString
。
This is my code:这是我的代码:
class EventDispatcher<T: EventData>(
val pubSubTemplate: PubSubTemplate
) {
/**
* Dispatch an event to the game engine event manager pipeline
*/
fun dispatchEvent(event: T, initiator: String) {
val eventData: String = Json.encodeToString(event)
}
The compiler tells me:编译器告诉我:
Cannot use `T` as reified type parameter. Use a class instead
Is there a way to make this still work?有没有办法让它仍然有效?
For Json.encodeToString(event)
to work, it needs the type information for T
.为了让
Json.encodeToString(event)
工作,它需要T
的类型信息。 But, this type information is lost at runtime due to the way how generics work in Kotlin/Java.但是,由于泛型在 Kotlin/Java 中的工作方式,这种类型信息在运行时会丢失。
One way to retain the type information would be by making dispatchEvent
an inline function with T
as a reified type parameter .保留类型信息的一种方法是使
dispatchEvent
成为内联函数,其中T
作为具体化的类型参数。
However, this also raises the question how you want to serialize event
.但是,这也提出了您希望如何序列化
event
。 You could also use polymorphic serialization of EventData
, rather than trying to serialize T
.您还可以使用
EventData
多态序列化,而不是尝试序列化T
。 This will include an additional class discriminator in your serialized output (it necessarily has to for polymorphic serialization/deserialization to work).这将在您的序列化输出中包含一个额外的类鉴别器(它必须使多态序列化/反序列化工作)。
If you serialize the concrete type T
, this class discriminator wouldn't be included, which is questionable;如果您序列化具体类型
T
,则不会包含此类鉴别器,这是有问题的; how would whoever will deserialize this know what type it is?反序列化的人如何知道它是什么类型?
In short, I think you need polymorphic serialization.简而言之,我认为您需要多态序列化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.