I'm looking for a way to serialize a specific clas...
# serialization
f
I'm looking for a way to serialize a specific class using a specific method in my
NamedValueEncoder
/
NamedValueDecoder
.
Copy code
class MyClass {
   /**  **/
}
Doing that in a
ElementValueEncoder
is simple enough :
Copy code
class MyEncoder : ElementValueEncoder(){
    fun encodeMyClass(obj : MyClass){
         /** **/
     } 
}
// And then in serializer...
@Serializer(forClass = MyClass)
object MyClassSerializer : KSerializer<MyClass> {
      override fun serialize(encoder: Encoder, obj: MyClass) {
        if(encoder is MyEncoder){
            encoder.encodeMyClass(obj)
        }
        else error("not supported")
    }  
}
However, I cannot see how I can do the same thing in a
NamedValueEncoder
, as it requires a tag, which I don't know how to generate.
Copy code
class MyTaggedEncoder : NamedValueEncoder(){
    fun encodeTaggedMyClass(tag: String, obj : MyClass){
         /** **/
     } 
}
// And then in serializer...
@Serializer(forClass = MyClass)
object MyClassSerializer : KSerializer<MyClass> {
      override fun serialize(encoder: Encoder, obj: MyClass) {
        if(encoder is MyTaggedEncoder){
            encoder.TaggedMyClass( ??????,      obj)
        }
        else error("not supported")
    }  
}
I don't have access to the methods that generate the tag, to be used in the area marked as "?????", as they are private in
NamedValueEncoder
. There are also no methods that allow
Any
class to be encoded in
NamedValueEncoder
(of which I don't need to provide a tag myself to) . So how can I encode / decode a tagged
MyClass
in this situtation?
s
You want to create encoder with custom support for
MyClass
? I think the right way to do it would be to check instance/class descriptor in the
encodeSerializableValue
function: https://github.com/Kotlin/kotlinx.serialization/blob/master/runtime/commonMain/src/kotlinx/serialization/protobuf/ProtoBuf.kt#L61
f
I'll try that, thanks