0

I love to use single-value types for e.g. IDs. How can I tell Kotlinx Serializer to consider such types as regular fields, not objects?

Example:

data class User(
    val id: UserId,
    val name: String,
)

should be serialized to:

{
  id: 123,
  name: "foo"
}

and UserId is just data class(val value: Int)?

EDIT: I guess I could use custom serializer for each Id class, but I really don't wanna repeat such code for each and every ID in my domain. Moreover, I am not sure how to write one; so far my effort is failing.

EDIT2: this is my attempt for writing such serializer:

open class DoctorIdSerializer : KSerializer<DoctorId> {
    override val descriptor: SerialDescriptor = PrimitiveDescriptor("id", PrimitiveKind.STRING)

    override fun serialize(encoder: Encoder, value: DoctorId) {
        encoder.encodeInt(value.value)
    }

    override fun deserialize(decoder: Decoder): DoctorId {
        return DoctorId(decoder.decodeInt())
    }
}

basically, whats written here but its not working :(

igr
  • 10,199
  • 13
  • 65
  • 111

0 Answers0