nkiesel
09/09/2021, 8:41 PMkoltin.time.Duration property of a data class in Kotlin 1.5.30 using Jackson 2.12.5. One immediate problem is that - because Duration is a value class - Jackson sees just a long value and thus serializes a Duration.seconds(10) as 20000000000. This is obviously not what I want because it exposes the internal "use high bit to differentiate nano from milli". I tried to register a custom serializer which extends JsonSerializer<Duration>() using @JsonSerialize but that is ignored (presumably because Jackson just sees a long value). The only way I see right now is to have an explicit durationAsString property and keep that in sync with the duration property. Is there a better way? Note: I think I cannot use Kotlin serialization because this is part of a mixed Java/Kotlin project. But if I could: would that solve the issue?ephemient
09/09/2021, 8:44 PMephemient
09/09/2021, 8:46 PMephemient
09/09/2021, 9:11 PM@ExperimentalTime
data class Foo(
@get:JsonIgnore
val dur: Duration
) {
@JsonCreator constructor(
@JsonProperty("dur")
dur: String
) : this(Duration.parse(dur))
@get:JvmName("getDur")
val _dur: String get() = dur.toString()
}nkiesel
09/09/2021, 9:27 PMnkiesel
09/09/2021, 9:43 PMkotlinx.serialization work by creating a object DurationAsStringSerializer : KSerializer<Duration> and annotating the property with @Serializable(with = DurationAsStringSerializer::class) . This looks cleaner (and easier to replicate) than the `@JsonIgnore`/`@JsonCreator`/`@JsonProperty`/`@JvmName` approach. I will see if using kotlinx.serializatin is really not an option for my project.ephemient
09/09/2021, 9:54 PM@file:Serializers(DurationAsStringSerializer::class) once at the top of the file, which is equivalent to adding @Serializable(with = ...) at every occurrence of Durationnkiesel
09/09/2021, 11:07 PMDuration)ephemient
09/09/2021, 11:14 PMnkiesel
09/09/2021, 11:25 PMDuration is especially tricky because it uses bit manipulation to encode type information (nanos vs. millis).ephemient
09/09/2021, 11:30 PM