Hi, Is it possible to use generated serializer and...
# serialization
n
Hi, Is it possible to use generated serializer and custom deserializer for some data class?
a
yes, that’s possible
n
How it can be achieved?
a
that’s quite a large question to ask! The docs are a good start https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/serializers.md but if something’s not working you need to be more specific https://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/
n
I was able to implement this by surrogate serializer but I would like avoid this method.
I just want a custom deserializer and generated serializer to avoid writing error prone code.
m
Something like this should work:
Copy code
@Serializable(with = MyClass.Serializer::class)
data class MyClass(val prop: Int) {
    @Serializer(forClass = MyClass::class)
    object Serializer : KSerializer<MyClass> {
        override fun deserialize(decoder: Decoder): MyClass {
            // custom logic here
        }
    }
}
(I've not tested it in a IDE and just wrote in Slack. Probably there is some syntax error or so) You might ask, why this works. Well, the
@Serializer
annotation generates the KSerializer, but skips those methods, that are implemented manually. In this case the deserialize method is defined manually, so the plugin just generates the serialize method and the descriptor.
n
It works. Thanks!
I just want to achieve one more thing. In
deserialize()
I'm adding additional things and at the end I would like to call there generated deserializer. At this moment I have it solved by created second data class with the same model. Is there a better way to achieve this?
m
You can add something like this:
Copy code
@Serializer(forClass = MyClass::class)
private object OriginalSerializer : KSerializer<MyClass>
Inside the
deserialize
from the
Serializer
object, you can then use
OriginalSerializer.deserialize(decoder)
.