Closed drammelt closed 2 years ago
Generally yes, you need to set the serializer explicitly, because on the jvm kvision types are just aliases to java.time.* types (unlike kotlinx-datetime
classes, which are custom classes annotated with @Serializable(with = ...)
annotations).
So do I need to do more than adding the
@file:UseContextualSerialization(LocalDateTime::class)
to the DTO? I cannot see anything else in the examples which compile and run fine for me.
It looks like you are creating a fullstack app, but you don't use KVision fullstack interfaces (at least within this Ktor route). Am I correct? All the examples are using KVision interfaces, where serializers are internally supported for datetime types.
You should be able to reuse KVision serializers module io.kvision.remote.kvSerializersModule
(defined here https://github.com/rjaros/kvision/blob/master/kvision-modules/kvision-common-remote/src/jvmMain/kotlin/io/kvision/remote/KotlinxObjectDeSerializer.kt#L46) within Ktor KotlinxSerializer()
configuration (https://ktor.io/docs/json.html#kotlinx).
Yes you are correct this is an AJAX endpoint for a Tabulator table.
You are a lifesaver thank you!
EDIT: Fixed solution, previous one had issues on the Frontend.
In case anyone comes across this the solution was...
Tabulator Table Ajax -> Backend API Endpoint
Use the Serializer from Kvision in the Backend side
@Serializer(forClass = LocalDateTime::class)
actual object JsonLocalDateTimeSerializer : KSerializer<LocalDateTime> {
override val descriptor: SerialDescriptor = buildClassSerialDescriptor("java.time.LocalDateTime")
override fun deserialize(decoder: Decoder): LocalDateTime {
@Suppress("MagicNumber")
return LocalDateTime.parse(
decoder.decodeString().split("[").first().dropLast(6),
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS")
)
}
override fun serialize(encoder: Encoder, value: LocalDateTime) {
encoder.encodeString(value.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS")))
}
}
Duplicate the common DTO on the Backend and annotate with
@file:UseSerializers(JsonLocalDateTimeSerializer::class)
So it is serialised to the format expected by KVision.
And on the JS annotate the common DTO with
@file:UseContextualSerialization(LocalDateTime::class)
Backend returns the Ajax DTO which will match the common code DTO and will be used without issue in the Kvision frontend.
I am getting this error at run time.
The common code DTO is as follows.
build.grade.kts commonMain
The values I am inserting into the DTO are from exposed DAO which are in java.time.LocalDateTime public final val createdAt: LocalDateTime / = java.time.LocalDateTime / public final val updatedAt: LocalDateTime / = java.time.LocalDateTime /
I double checked my code against the examples and can find no real differences.
If I change to kotlinx-datetime to serialize the localdatetime instead of the kvision class I have no issues.
Do I need to explicitly set the Serilizer for the kvision LocalDateTime?