kotlinx.serialization
kotlinx.serialization copied to clipboard
Serialization of value class kotlin.time.Duration does not work
Trying to use the value class Duration
with kotlin 1.5 and serialization 1.2 states
kotlinx.serialization.SerializationException: Serializer for class 'Duration' is not found.
Mark the class as @Serializable or provide the serializer explicitly.
My expectation is that value classes would "simply work". The Duration
class is not owned by me but the kotlin platform so attaching a @Serializable
annotation is not possible.
To Reproduce
@Serializable
data class MyObject(
val time: Duration = Duration.ZERO
)
Expected behavior Serialize.
Environment
- Kotlin version: 1.5.0
- Library version: 1.2.0
- Kotlin platforms: JVM
- Gradle version: 7.x
Which format? You could also write a custom serializer, I think.
No, serialization of inline classes won't 'just work', they should be marked serializable themselves. We'll investigate Duration serialization soon
@sandwwraith Thanks for the info. This would apply to all bundled values classes of course.
Hi there!
Do you have an update on this ticket? Still an issue on 1.6.10
.
implementation("org.jetbrains.kotlinx:kotlinx-datetime:0.3.1")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.2")
Thanks for reminder, we'll update the priority
No, serialization of inline classes won't 'just work', they should be marked serializable themselves. We'll investigate Duration serialization soon
This didn't age well...
Still getting the same issue, no serializer for Duration
The latest 1.4.0-RC release contains a serializer for Duration
.
Plugin support (i.e. automatically detect that Duration
is serializable) comes in 1.7.20
I personally went with custom contextual serializer (https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/serializers.md#contextual-serialization) a while ago, but obviously better to have OOTB support for such core classes, thanks for great news :)
Yeah, that's what I did too, it thankfully has methods to output to iso string and parse back from it, which makes you question even more the problem :)
Here's some sample code, if it helps those trying pre-1.7.20
@Serializable
data class Example(
@Serializable(with = DurationSerializer::class)
val time: Duration
)
object DurationSerializer : KSerializer<Duration> {
private val serializer = Duration.serializer()
override val descriptor: SerialDescriptor = serializer.descriptor
override fun deserialize(decoder: Decoder): Duration =
decoder.decodeSerializableValue(serializer)
override fun serialize(encoder: Encoder, value: Duration) {
encoder.encodeSerializableValue(serializer, value)
}
}
Fixed in 1.7.20/1.4.0
Edit:
Wrong alarm. I was using java time. Keeping original post below the line.
are we sure if this is deployed? On my end, Duration is not still serializable by default.
version.kotlinx.serialization=1.4.1
version.kotlin=1.7.20