Skip to content

Q: How to not write a CBOR tag when value is null? #2966

@travishaagen

Description

@travishaagen

For CBOR serialization, I assign a tag as so,

@Serializable
data class Something(
    @ValueTags(MY_TAG) @Contextual val myObject: MyObject?
)

and I have a serializer like

object MyObject AsByteArraySerializer : KSerializer<MyObject> {
    override val descriptor: SerialDescriptor
        get() = SerialDescriptor("MyObject", ByteArraySerializer().descriptor)

    override fun deserialize(decoder: Decoder): MyObject = MyObject(decoder.decodeSerializableValue(ByteArraySerializer()))

    override fun serialize(
        encoder: Encoder,
        value: MyObject,
    ) = encoder.encodeSerializableValue(ByteArraySerializer(), value.toBytes())
}

It works fine for non-null values, but when null, I don't want the tag written to the byte stream. I need to do this to be in compliance with another project's CBOR protocol expectations.

For example, right now, when the value is null, I'm writing a tag,

      70726576                          # "prev"
   D8 2A                                # tag(42)
      F6                                # primitive(22)

but I need it not to write the tag

      70726576                          # "prev"
   F6                                   # primitive(22)

what can I do to control this?

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions