kotlinx.serialization
kotlinx.serialization copied to clipboard
Allow to set serializer for a class in Json intialization
I would be great if we had an option to set serializer for a class during Json initialization or in serializers module. Something like this:
Json {
useSerializer(SomeClass::class, CustomSerializer)
}
or
SerializersModule {
useSerializer(SomeClass::class, CustomSerializer)
}
It would allow us to set/ovveride serializer for a class from a library which is out of our control.
For example in my app I would like to serialize kotlinx.datetime.Instant as a number of miliseconds but the class is annotated @Serializable(with = InstantIso8601Serializer::class) and I can't change it.
Check out https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/serializers.md#specifying-serializers-for-a-file and also https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/serializers.md#contextual-serialization. These serializers always have higher priority than a @Serializable(with=...) on a class and can be configured per file. Does this solve your problem?
I second @sandwwraith suggestion.
Regarding the initial request, it doesn't seem to be possible from the API perspective -- SerializersModule is meant to be immutable, so basically there are only two options:
- Overwrite the current module with a new one, that contains added
useSerializer. Such solution is counter-intuitive and may expose surprising behaviour, e.g.:
Json {
serializersModule = someProjectSpecificModuleThatCustomlyRegisteredSerializersRelyOn
useSerializer(...)
}
- Mix in
SerializersModuleBuilderintoJsonreceiver. Things will get even more confusing with bothserializersModule = someObjectand `serializersModule = SerializersModule { /* here we got 'this' of the same type, but it's different object that is easy to miss */ }
Check out https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/serializers.md#specifying-serializers-for-a-file and also https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/serializers.md#contextual-serialization. These serializers always have higher priority than a
@Serializable(with=...)on a class and can be configured per file. Does this solve your problem?
Thank you for reply. I've seen this but I don't think it's a good option. I would like to set it for the whole project to be sure the same serializer is used everywhere. Annotating every single case (or file) is a bit painful and may lead to errors when someone forget it.