How/Can I use a custom KSerializer?
See original GitHub issueIs it possible to use a custom defined KSerializer
to store an object that does not have the @Serializable
annotation defined? For example, let’s say I want to store a Date
using the kotlinxPref
delegate – basing this on the https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/serializers.md#serializing-3rd-party-classes example.
I’ve defined a KSerializer
in my Kotlin file.
@file:UseSerializers(DateAsLongSerializer::class)
object DateAsLongSerializer : KSerializer<Date> {
override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("Date", PrimitiveKind.LONG)
override fun serialize(encoder: Encoder, value: Date) = encoder.encodeLong(value.time)
override fun deserialize(decoder: Decoder): Date = Date(decoder.decodeLong())
}
And created a SerializersModule
so that I can set that in the json extension property.
val module = SerializersModule {
contextual(DateAsLongSerializer)
}
And then defined a SimpleKrate
as;
class DateKrate(context: Context) : SimpleKrate(context) {
init {
json = Json { serializersModule = module }
}
var currentDate: Date? by kotlinxPref("current-date")
}
But when I try to assign a value to that Krate I get the following exception.
Serializer for class 'Date' is not found. Mark the class as @Serializable or provide the serializer explicitly.
Any ideas of what I might be doing wrong here? (Thanks for creating this great library btw)
Edit:
The alternative is to just store it as a private longPref
and define a getter/setter which casts the value to and from a long. Just curious though on the use of the KSerializer
.
Issue Analytics
- State:
- Created 2 years ago
- Comments:10
Top GitHub Comments
Ah, got it. Back in
1.0.0
, the publishing script I was using was incorrect, and pulled in too many things as acompile
dependency, exposing them transitively despite them being listed asimplementation
dependencies. I fixed this in later versions.You can follow the upcoming release here https://github.com/AutSoft/Krate/pull/24
Got a bunch of other things to include in it too