I'm making my own implementation of AbstractEncoder for a goal of digest, trying to ignore specific interface when implementing Encoder. I have an interface:
interface HasId {
val Id: Int
}
and various classes implementing it:
@Serializable
data class A(val j: Int, override val Id: Int) : HasId
@Serializable
data class B(val bunchOfOtherStuff : Bunch, val k: Int, override val Id: Int) : HasId
Those types are also serialized for other reasons that do need the Id to be included. Given that I have an interface for indication, how can I ignore it without implementing a bunch of serializers manually?
Currently, I have tried this:
class MyEncoder : AbstractEncoder { ...
override fun encodeElement(descriptor: SerialDescriptor, index: Int): Boolean {
val elem = descriptor.getElementDescriptor(index)
val isNeedSerialization = !(elem.kind == PrimitiveKind.INT && descriptor.getElementName(index) == "Id")
if (!isNeedSerialization) {
println("skip serializing ${elem.serialName}")
}
return isNeedSerialization
}
}
And it works, but will fail on the class that doesn't inherit from HasId:
data class C(val j: Int, val Id: Int)
Thought of something like:
override fun <T : Any?> encodeSerializableElement(
descriptor: SerialDescriptor,
index: Int,
serializer: SerializationStrategy<T>,
value: T
) {
if (value is HasId) {
//pass a descriptor or serializer that will ignore it
}
else super.encodeSerializableElement(...)
}