Is there any stable way of serializing into a Byte...
# serialization
a
Is there any stable way of serializing into a ByteArray without any significant size overhead? Basically looking for an alternative to Android Parcelable.
j
Depends on the data, really. Is it key-heavy and value-light? Proto. Is it key-light and value-heavy? Maybe cbor. Custom format also is a possibility if you know the structure a bit.
a
Is it possible to avoid keys completely? Just encode values in order, and then decode in the same order. Also, could you please point me on custom formats? And I would need this in a library, so looking for stable solutions.
l
How do you plan on handling new/removed fields without keys? If you can ignore those cases, you may be able to create a custom serializer that appends to a ByteArray for each field.
h
How you you plan to deserialize the data? Do you need a delimiter? Otherwise, you could use a fixed length format. This requires to serialize the values in order and you need to handle empty values/new attributes with care.
a
There's an example in the docs that encodes the values in binary https://github.com/Kotlin/kotlinx.serialization/blob/v1.6.0/docs/formats.md#efficient-binary-format. I used it in a hobby project that was 100% Kotlin and it worked well. The example uses Java library classes, but it's possible to replace those with Okio types. to make it multiplatform (example).
a
Thanks Adam, that Efficient binary format looks like what I need. As I'm looking for an alternative for Android Parcelable for state preservation, I don't care about backward or forward compatibility. Though, AbstractEncoder is not stable for inheritance, so most likely I won't be able to use it in a library. Would be nice to have that in kotlinx-serialization as a stable solution. But thaks anyway.