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

SealedClassSerializer doesn't handle value classes correctly #2839

Closed
valeriyo opened this issue Oct 21, 2024 · 1 comment
Closed

SealedClassSerializer doesn't handle value classes correctly #2839

valeriyo opened this issue Oct 21, 2024 · 1 comment

Comments

@valeriyo
Copy link

Describe the bug
SealedClassSerializer doesn't serialize value subclasses into the expected structure, with type property. Instead it just dumps the raw value, which won't deserialize back!

To Reproduce
See test below

Expected behavior
Instead of raw value, the resulting JSON should be of the same structure, as regular subclasses: "{"type":".......","value":......}"

Environment

  • Kotlin version: 2.0.21
  • Serialization: 1.7.3
  • Gradle 8.8
  • Android Studio Ladybug
import kotlin.test.assertEquals
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import org.junit.Test

@Serializable
sealed interface Sealed {

 @Serializable
 @SerialName("DataObject")
 data object DataObject : Sealed

 @Serializable
 @SerialName("DataClass")
 data class DataClass(val code: Int) : Sealed

 @Serializable
 @SerialName("ValueClass")
 @JvmInline
 value class ValueClass(val code: Int) : Sealed
}

class SealedTest {

 @Test
 fun test() {
   val serializer = Sealed.serializer()

   assertEquals(
     expected = "{\"type\":\"DataObject\"}",
     actual = Json.encodeToString(serializer, Sealed.DataObject),
   )

   assertEquals(
     expected = "{\"type\":\"DataClass\",\"code\":111}",
     actual = Json.encodeToString(serializer, Sealed.DataClass(111)),
   )

   assertEquals(
     expected = "222", // WRONG! should be "{\"type\":\"DataClass\",\"value\":222}"
     actual = Json.encodeToString(serializer, Sealed.ValueClass(222)),
   )
 }
}
@sandwwraith
Copy link
Member

This is caused by the fact that your ValueClass is an inline class over Int. There is simply nowhere to add type, because Int is not an object. See #2049 (comment)

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