What's the recommended approach when creating a ne...
# serialization
c
What's the recommended approach when creating a new format that has more primitive types than JSON? I'm adding BSON, which has
ObjectId
,
Uuid
,
Timestamp
etc as primitive types. However,
KSerializer
doesn't have the equivalent
.encodeObjectId
,
.decodeObjectId
etc methods. I want users to be able to write custom serializers that take advantage of these primitive types. Also, these serializers should still work with other formats (with an appropriate fallback, for example
ObjectId
can be represented as an hex-encoded string in JSON).
e
`SerialKind`/`PrimitiveKind` are
sealed
so the obvious way of doing it isn't possible
but you could use an existing kind and an annotation to mark your extended primitive types instead
it might be annoying if you want
kotlin.uuid.Uuid
to work by default though, you might have to special case
if (serializer.descriptor == Uuid.serializer().descriptor)
in your format's `encodeSerializableValue`/`decodeSerializableValue`
c
you might have to special case
That"s what I'm doing at the moment, but I have no idea if that's a good practice or not.
use an existing kind and an annotation to mark your extended primitive types instead
Is there documentation on how to do that?
e
KxS primitives are not about the format but about language so I wouldn’t expect something like this to be supported.
Is there documentation on how to do that?
Mark a custom annotation with
@SerialInfo
, that means that when your users put that custom annotation on a class / property, then the annotation will be added to the
annotations
property of the descriptor as metadata that you can use while serializing or deserializing
a
> you might have to special case
That"s what I'm doing at the moment, but I have no idea if that's a good practice or not.
I think that's expected. The 'Efficient binary format' example handles ByteArrays specially, by checking if
serializer.descriptor == byteArraySerializer.descriptor
. https://github.com/Kotlin/kotlinx.serialization/blob/v1.9.0/docs/formats.md#format-specific-types
🙏 1