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

Fix issue #2938. Add check for sealed value class when serializing. #2940

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/*
* Copyright 2017-2025 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/

package kotlinx.serialization.json.polymorphic

import kotlinx.serialization.json.Json
import kotlin.jvm.JvmInline
import kotlin.test.Test
import kotlin.test.assertFailsWith

class InvalidPolymorphicTypeTest {
sealed interface InvalidType
enum class InvalidEnum : InvalidType {
A, B
}
@JvmInline
value class InvalidInline(val value: Int) : InvalidType

@Test
fun invalidEnum() {
assertFailsWith<IllegalArgumentException> {
Json.encodeToString<InvalidType>(InvalidEnum.A)
}
}

@Test
fun invalidInline() {
assertFailsWith<IllegalArgumentException> {
Json.encodeToString<InvalidType>(InvalidInline(1))
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,11 @@ private fun validateIfSealed(
classDiscriminator: String
) {
if (serializer !is SealedClassSerializer<*>) return

if (actualSerializer.descriptor.run { isInline && getElementDescriptor(0).kind is PrimitiveKind }) {
error("Value class that contains primitive kind cannot be serialized polymorphically with 'type' parameter. You can use 'JsonBuilder.useArrayPolymorphism' instead")
}

@Suppress("DEPRECATION_ERROR")
if (classDiscriminator in actualSerializer.descriptor.jsonCachedSerialNames()) {
val baseName = serializer.descriptor.serialName
Expand Down