Alexey Zolotarev
02/06/2025, 8:42 AM@Serializable
sealed interface Wrapper
@Serializable
@JvmInline
value class StringWrapper(val value: String): Wrapper
@Serializable
@JvmInline
value class IntegerWrapper(val value: Int): Wrapper
@Serializable
@JvmInline
@OptIn(ExperimentalSerializationApi::class)
value class BinaryWrapper(@ByteString val value: ByteArray): Wrapper
class DataTreeValueSerializationTest {
@OptIn(ExperimentalSerializationApi::class, ExperimentalStdlibApi::class)
@Test
fun testSerialization() {
val data = IntegerWrapper(1)
val serialized = Cbor.encodeToByteArray(Wrapper.serializer(), data)
println(serialized.toHexString())
val deserialized = Cbor.decodeFromByteArray(Wrapper.serializer(), serialized)
assertEquals(data, deserialized)
}
}
This for example is encoded this way:
Diagnostic:
[
_ "IntegerWrapper",
1
]
Commented:
9f -- Array (streaming)
6e -- String, length: 14
496e746567657257726170706572 -- [0], "IntegerWrapper"
01 -- [1], 1
ff -- BREAK
0x9f6e496e74656765725772617070657201ff
And I would like to have it [1]
in this case. The interface is sealed and there is only one possible class that corresponds to an integer, IntegerWrapper
so it should be possible to encode/decode it without any ambiguity.
With JSON by the way this doesn't work at all since it encodes the data to "1" in this case but then expects an object on deserialization.Alexey Zolotarev
02/06/2025, 11:11 AMpeek
method that would allow to analyze the tag. This makes extending it pretty difficult.Alexey Zolotarev
02/06/2025, 11:12 AMCborObject
sort of thing similar to JsonObject
in the Json decoder because of the same issue