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

Contextual serializer is ignored in serializerOrNull function #1870

Closed
rsinukov opened this issue Feb 21, 2022 · 1 comment
Closed

Contextual serializer is ignored in serializerOrNull function #1870

rsinukov opened this issue Feb 21, 2022 · 1 comment
Assignees

Comments

@rsinukov
Copy link
Contributor

Describe the bug

To Reproduce

    @Test
    fun testContextualByType() {
        val json = Json { serializersModule = serializersModuleOf(UserData::class, UserSerializer) }
        val type = typeOf<UserData>()
        val serializer = json.serializersModule.serializerOrNull(type)
        assertEquals(UserSerializer, serializer)
    }

    @Serializable
    public data class UserData(val id: Int, val name: String)

    public object UserSerializer : KSerializer<UserData> {
        override val descriptor: SerialDescriptor = buildClassSerialDescriptor("UserData")
        override fun deserialize(decoder: Decoder): UserData = TODO()
        override fun serialize(encoder: Encoder, value: UserData) = TODO()
    }   

Expected behavior
The test should pass.

I believe that the problem is in these lines inside serializerByKTypeImpl function.

    val result: KSerializer<Any>? = when {
        typeArguments.isEmpty() -> rootClass.serializerOrNull() ?: getContextual(rootClass)
        else -> builtinSerializer(typeArguments, rootClass, failOnMissingTypeArgSerializer)
    }?.cast()

The expression rootClass.serializerOrNull() ?: getContextual(rootClass) should be the opposite: first try to get contextual and if it's not found, fallback to default serializer.

Environment

  • Kotlin version: [e.g. 1.6.10]
  • Library version: [e.g. 1.3.0]
@sandwwraith
Copy link
Member

I think we won't change the semantics of the existing stable function in such an unpredictable way for users (see also #2026). Whether we should provide a new function that prioritizes module over built-in is an open question.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants