How to handle serialization with a class hierarchy

What is your use-case and why do you need this feature?
I need to serialize some classes like the following.

interface WalletRequest

@Serializable
data class Create(val user: String, val amount: Double) : WalletRequest

@Serializable
data class Transfer(val from: String, val to: String, val amount: Double) : WalletRequest

@Serializable
data class Amount(val user: String) : WalletRequest

val walletRequestModule = SerializersModule {
    polymorphic(WalletRequest::class) {
        Create::class with Create.serializer()
        Transfer::class with Transfer.serializer()
        Amount::class with Amount.serializer()
    }
}
fun walletRequestCbor(): Cbor = Cbor(context = walletRequestModule)

fun loadWalletRequestCbor(array: ByteArray): WalletRequest =
    walletRequestCbor().load(PolymorphicSerializer(WalletRequest::class), array)

in my case i would have N classes similar to the above with minor changes, one obvious solution would be having all of them extending the same interface, however it doesn’t feel like the cleanest solution…

Describe the solution you’d like
I experimented with having a global interface that would include all the contexts needed, i’ve designed an example bellow:

interface Requests

val requestsModule = SerializersModule {
    include(walletRequestModule)
    include(contractRequestModule)
}

fun requestsCbor(): Cbor = Cbor(context = requestsModule)

fun loadRequest(array: ByteArray): Requests =
    requestsCbor().load(PolymorphicSerializer(Requests::class), array)

however this example produces the following error:

kotlinx.serialization.SerializationException: io.csd.endpoints.wallet.Create is not registered for polymorphic serialization in the scope of class io.csd.endpoints.Requests

any suggestion is welcomed!

2 Likes