Override val descriptor: SerialDescriptor = surrogateSerializer. All subclasses of a sealed class must be. Private val surrogateSerializer = rializer(tSerializer) The most straightforward way to use serialization with a polymorphic hierarchy is to mark the base class sealed. mirai-console-plugin-cytoidinfo / src / main / kotlin / PlayerProfile.kt Go to file Go to file T Go to line L Copy path. for "Error" data: T? = exceptionMessage: String? = null The annotation is not necessary, but it avoids serializing "data = null" ) : KSerializer> class ServiceResultSurrogate( = ServiceResultSerializer::class)ĭata class Success(val data: T) : ServiceResult()ĭata class Error(val exceptionMessage: String?) : ServiceResult() Kotlinx serialization favors sealed base serializer even when explicitly using subclass Litote/kmongo310 Sign up for free to join this conversation on GitHub. For the sake of simplicity in the example I only represent the exception message. Applying Serializable to the Kotlin class instructs the serialization plugin to automatically generate implementation of KSerializer for the current class, that can be used to serialize and deserialize the class. Sealed classes are also implicitly abstract. The main entry point to the serialization process. Those issues can however be resolved with custom configurations. 'jackson-module-kotlin' does a good job in general, but lacks some functionality for handling sealed case classes. As Animesh Sahu already mentioned there is an issue for this topic that is still open, but the solution using a surrogate suggested by Михаил Нафталь for serialization of Error can actually be used also to serialize the polymorphic ServiceResult, by creating a surrogate that mixes the fields of Success and Error. As of Kotlin 1.5, sealed classes can have subclasses in all files of the same compilation unit and the same package. Serialization of Kotlin Sealed Case Classes This repository shows how to serialize and deserialize kotlin sealed cases classes using Jackson.
0 Comments
Leave a Reply. |