Hello! I’m attempting to serialize a ByteArray int...
# serialization
t
Hello! I’m attempting to serialize a ByteArray into CBOR using the data type 2 (ByteString). This is achieved using an annotation on ByteArray fields of a class as explained here: https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-cbor/kotlinx.serialization.cbor/-byte-string/. The serialization inside the class works well and is in line with other implementations. My issue is that I need to serialize/deserialize a single value rather than a property in a class, but I don’t know how to apply this annotation to a ByteArray in general rather than on a property inside a class. Are there any examples of this somewhere? Is it just so simple that it’s not mentioned? If so I’d love a tip on how to do it! Here is an example:
Copy code
@OptIn(ExperimentalSerializationApi::class)
@Serializable
public class Animal(
    @ByteString
    public val animal: ByteArray
)

val encoder = Cbor.Default
val cbor: ByteArray = encoder.encodeToByteArray(Animal.serializer(), animal)
println("The cbor data is ${cbor.toHexString()}"
This encodes the ByteArray correctly, but it’s still wrapped up inside encoding for the class, whereas I’d like it to have it “raw”. Cheers!
h
I don’t know if it will work but you could try using a value class. Or check the implementation what this annotation does under the hood and try to call this method by yourself.
t
Yeah I tried value classes. Doesn’t work unfortunately. But I’ll dig into the annotation code that’s a great idea. Found more issues on this: https://github.com/Kotlin/kotlinx.serialization/issues/2187 https://github.com/Kotlin/kotlinx.serialization/issues/2037 https://github.com/Kotlin/kotlinx.serialization/pull/2412