My question started out about how to rewrite a Jso...
# serialization
j
My question started out about how to rewrite a JsonTransformingSerializer as a KSerializer. I think that is now resolved. My remaining question is whether a new serializer can be made to be the default for a type so it doesn’t need to be annotated every time.
I am using a JsonTransformingSerializer to help fix an incompatible formatting error. I’d like to be able to use the same transformer with both Json and Properties. Is this possible?
Copy code
class DateFixer: JsonTransformingSerializer<Instant>(Instant.serializer()) {
    override fun transformDeserialize(element: JsonElement): JsonElement = JsonPrimitive(fixBasicTz(element.jsonPrimitive.content))
}

@Serializable
data class MyData(
    @Serializable(with = DateFixer::class)
    val date: Instant? = null
)
It makes sense that with
Properties
I get the error
Copy code
This serializer can be used only with Json format.Expected Encoder to be JsonEncoder, got class kotlinx.serialization.properties.Properties$OutAnyMapper (Kotlin reflection is not available)
I started using
JsonTransformingSerializer
as a model to try to write a generic KSerializer but I quickly see it uses Json specific encoders and decoders. I am wondering if there is an easy way to write a generic transformer.
Oh, I think I got something that works:
Copy code
class DateFixer: KSerializer<Instant> {
    private val tSerializer = Instant.serializer()

    override val descriptor: SerialDescriptor get() = tSerializer.descriptor

    override fun deserialize(decoder: Decoder): Instant {
        return Instant.parse(fixBasicTz(decoder.decodeString()))
    }

    override fun serialize(encoder: Encoder, value: Instant) {
        encoder.encodeSerializableValue(tSerializer, value)
    }
}
Of course as I look with some increased understanding I find a number of resources including https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/serializers.md. I’m wondering though is it possible to define a new default serializer for all
Instant
types so that I don’t have to be sure to decorate each occurrence in a serializable class?
e
@file:UseSerializers(DateFixer::class)
at the top of a file will apply to all
Instant
types (that are not otherwise annotated) in serializable classes defined within the same file
j
Awesome! Thank you again.
Oh, again, once you mention it, I can find it written. The docs actually seem to be really thorough. Now if only I could search more effectively.
Am I reading correctly that there isn’t an option for making it the project wide default?
e
there isn't
you could install a contextual serializer in the serializersModule, but that still requires a
@Contextual
annotation on all the use sites
🙏 1