What am I doing wrong in the following snippet? I...
# serialization
v
What am I doing wrong in the following snippet? Important: The answer is not that I do not simply annotate with
@Serializable
.
Foo
in reality is a Groovy object from a library so it is not modifiable.
Copy code
data class Foo(val count: Int = 1)

@Serializer(forClass = Foo::class)
object FooSerializer : KSerializer<Foo> {
    override val descriptor = SerialDescriptor("Foo") {
        element("count", Int.serializer().descriptor)
    }

    override fun deserialize(decoder: Decoder) = decoder.decodeStructure(descriptor) {
        Foo(decodeIntElement(descriptor, 0))
    }

    override fun serialize(encoder: Encoder, value: Foo) {
        encoder.encodeStructure(descriptor) {
            encodeIntElement(descriptor, 0, value.count)
        }
    }
}

println(Json(Stable).parse(FooSerializer, Json(Stable).stringify(FooSerializer, Foo())))
Result:
Copy code
Unexpected JSON token at offset 14: Failed to parse 'int'.
   JSON input: {
      "count": 1
  }
Because it tries to parse
count
as
Int
instead of
1
:-/
Ah, I see, I have to do it like
Copy code
override fun deserialize(decoder: Decoder) = decoder.decodeStructure(descriptor) {
        when(decodeElementIndex(descriptor)) {
            READ_DONE -> Foo()
            else -> Foo(decodeIntElement(descriptor, 0))
        }
    }