Protobuf serialization in kotlin
Are you intending to align with kotlinx.serialization? In the general case, I would advise doing so - this is the emerging standard for Kotlin serialization which spans serialization formats (JSON, CBOR, and Protobuf first supported) and is designed to work with multi-platform.
More on reddit.com
kotlin - How to serialize a library class to Protobuf with kotlinx.serialization? - Stack Overflow
kotlin - How to parse protobuf message in kotlinx serialization - Stack Overflow
Why should I use kotlinx.serialization?
Hello, want to use protobuf to serialize a large string object to be stored in realm, as of now using JSON which is causing huge object memory. But not sure how can I use protobuf to achieve this as there are very little online examples that isn't relevant to my usecase. protobuf uses schema (.proto) file and serialize this file so that we can use it but in my case I will get string from response that needs serialization, any help would be much appreciated.
Are you intending to align with kotlinx.serialization? In the general case, I would advise doing so - this is the emerging standard for Kotlin serialization which spans serialization formats (JSON, CBOR, and Protobuf first supported) and is designed to work with multi-platform.
It's hard to do protobuf serialization without knowing the fields and type up front, that is why you are not seeing much examples on dynamic serialization.
There is no type information embedded within the protobuf message, only data. You can of course be "dynamic" by having a string field that stores your JSON, but that is not really optimal usage.
The process is usually like this:
-
Create protobuf definitions (.proto)
-
Use gradle or maven to compile protobuf to Java
-
Either build and distribute a jar with the compiled classes, or import the generated into your IDE
-
In your code, manually build an object based on your generated classes
-
Serialize it by calling toByteArray()
-
Deserialize to a new object by calling MyClass.parseFrom(byteArray)
There is not really much difference from Java here. While there is the possibility to have fields varying on the content, it is not meant for dynamic objects, it's strength is in keeping a semi-rigid structure with evolvability when passing (or storing) data between different systems.
If your goal is to save storage space, just gzip your json instead.