There is good documentation for the latest version of kotlinx.serialization https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/serializers.md#custom-serializers
However, there is no PrimitiveSerialDescriptor
class in the question which means, that some older version of kotlinx.serialization is used.
From https://github.com/Kotlin/kotlinx.serialization/releases it could be found out that in version 1.0.0-RC
PrimitiveDescriptor
was renamed to PrimitiveSerialDescriptor
and
The id of the core artifact with @Serializable
annotation and Json
format was changed from kotlinx-serialization-runtime
to kotlinx-serialization-core
to be more clear and aligned with other kotlinx libraries.
Following that, here is an example of code for kotlinx.serialization version 0.20.0:
object DateSerializer : KSerializer<Date> {
override val descriptor = PrimitiveDescriptor("Date", PrimitiveKind.LONG)
override fun serialize(encoder: Encoder, value: Date) = encoder.encodeLong(value.time)
override fun deserialize(decoder: Decoder): Date = Date(decoder.decodeLong())
}
@Serializable
data class MyDto(
@Serializable(DateSerializer::class)
val date: Date
)
fun main() {
val dto = Json.parse(MyDto.serializer(), """{ "date" : 1630407000000 }""")
println(dto.date)
}
with build.gradle.kts
plugins {
kotlin("jvm") version "1.3.72"
kotlin("plugin.serialization") version "1.3.72"
}
repositories { mavenCentral() }
dependencies {
implementation("org.jetbrains.kotlinx", "kotlinx-serialization-runtime", "0.20.0")
}
Unresolved reference: PrimitiveSerialDescriptor
which doesn't resolve – Ruckimport kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
? – PaniLong
. Conversions is not what a @Serializable is for. – Selfdriven