You are currently viewing Creating a custom serializer that encodes an object as a ByteArray

Creating a custom serializer that encodes an object as a ByteArray

I have a class called ByteArraySegment, which is a simple immutable wrapper around a ByteArray. I want to make it @Serializable and for its serialized form to be a plain ByteArray.

I’ve been trying to follow the docs to do this, and here is my attempt so far:

@Serializer(forClass = ByteArraySegment::class) companion object : KSerializer<ByteArraySegment> { override val descriptor: SerialDescriptor get() = ByteArraySerializer().descriptor override fun serialize(encoder: Encoder, value: ByteArraySegment) { encoder.encode(ByteArraySerializer(), value.asArray) } override fun deserialize(decoder: Decoder): ByteArraySegment { return ByteArraySegment(decoder.decode(ByteArraySerializer())) } } 

Unfortunately I get the following error when I try to serialize a ByteArraySegment:

java.lang.ClassCastException: class locutus.tools.ByteArraySegment cannot be cast to class [B (locutus.tools.ByteArraySegment is in unnamed module of loader 'app'; [B is in module java.base of loader 'bootstrap')` 

Would appreciate it if anyone has any ideas on what I’m doing wrong, as I’ve been blocked on this problem for a while.

submitted by /u/sanity
[link] [comments]