https://kotlinlang.org logo
Title
n

nacyolsa

02/07/2023, 3:57 PM
Hi, Is it possible to use generated serializer and custom deserializer for some data class?
a

Adam S

02/08/2023, 9:07 AM
yes, that’s possible
n

nacyolsa

02/08/2023, 9:10 AM
How it can be achieved?
a

Adam S

02/08/2023, 9:15 AM
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

nacyolsa

02/08/2023, 9:16 AM
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

molikuner

02/08/2023, 1:26 PM
Something like this should work:
@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

nacyolsa

02/08/2023, 3:21 PM
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

molikuner

02/08/2023, 3:26 PM
You can add something like this:
@Serializer(forClass = MyClass::class)
private object OriginalSerializer : KSerializer<MyClass>
Inside the
deserialize
from the
Serializer
object, you can then use
OriginalSerializer.deserialize(decoder)
.