Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Obtaining a deserializer for a subclass of a sealed class from just the class discriminator value #1802

Open
inthewaves opened this issue Dec 22, 2021 · 0 comments
Labels

Comments

@inthewaves
Copy link

inthewaves commented Dec 22, 2021

What is your use-case and why do you need this feature?

I am working with a JSON protocol where some messages have the following structure:

sealed class TypedException

sealed class JsonMessageWrapper<out Response> {
    public abstract val data: Response?

    public open val error: TypedException? = null

    public open val errorType: String? = null
}

The class discriminator for the TypedException is the errorType which is in the parent object. The JSON body doesn't include the class discriminator in the nested object itself, making it harder to just use the generated serializers as is.

Describe the solution you'd like

(I did notice #686 and #471, and there's probably a better way to handle this entire situation with aJsonContentPolymorphicSerializer, although the type variable in JsonMessageWrapper might make things a bit more complex)

Currently, the class is structured like this:

sealed class JsonMessageWrapper<out Response> {
    public abstract val data: Response?

    public open val error: JsonObject? = null

    public open val errorType: String? = null
}

I'm currently working with obtaining a polymorphic deserializer for the TypedException based on the value of the errorType :

val deserializer: DeserializationStrategy<out TypedExceptionV1> = jsonInstance.serializersModule.getPolymorphic(TypedExceptionV1::class, response.errorType)!!
val typedExceptionBody: TypedExceptionV1 = jsonInstance.decodeFromJsonElement(deserializer, response.error!!)

For this method, all the sealed subclasses of TypedException had to be registered with the serializersModule. I am wondering if there is a way to obtain a deserializer for a sealed class from just providing a class discriminator value without needing to register them all in the module.

@inthewaves inthewaves changed the title Deserializing a sealed class where the class discriminator is one level above Obtaining a deserializer for a subclass of a sealed class from just the class discriminator value Dec 22, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant