Is there a way to write a `KSerializer` for a clas...
# serialization
s
Is there a way to write a
KSerializer
for a class that allows conditionally skipping the related field?
@Transient
does it every time, but I'd like to exclude a field if some condition is met (similar to how default values can be excluded with an option). If I just don't do anything in my
serialize()
method the key is still present and I get
{"key":}
, which is not ideal. Desirable result would be
{}
. Arbitrary example where negative integer values would not be encoded (actual use case is more complex):
Copy code
@Serializable
data class SomeClass(@Serializable(with = SkipNegativeValues::class) val key: Int)

Object SkipNegativeValues : KSerializer<Int> {
    override fun serialize(encoder: Encoder, value: Int) {
        if (value >= 0) {
            encoder.encodeInt(value)
        }
    }
}
I suppose one way would be writing a serializer for SomeClass and skipping it manually but that is a bit of a pain for a large project where this occurs often. Hoping I can automate it somehow, like some sort of
shouldSerialize(value)
method I can override or something.