Stijndcl
08/03/2024, 3:38 PMKSerializer
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):
@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.