commonMain.com.bselzer.ktx.datetime.serialization.DurationSerializer.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of ktx-datetime-jvm Show documentation
Show all versions of ktx-datetime-jvm Show documentation
Extensions for the Kotlin standard library and third-party libraries.
The newest version!
package com.bselzer.ktx.datetime.serialization
import kotlinx.serialization.KSerializer
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlin.time.Duration
/**
* A serializer for [Duration] using a string representation.
*/
class DurationSerializer: KSerializer {
override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("Duration", PrimitiveKind.STRING)
override fun deserialize(decoder: Decoder): Duration = Duration.parse(decoder.decodeString())
override fun serialize(encoder: Encoder, value: Duration) {
encoder.encodeString(value.toIsoString())
}
}