Is there an easy way to write something like ```@Serializable data class Foo( val date: @Seriali...
c
Is there an easy way to write something like
Copy code
@Serializable
data class Foo(
    val date: @SerializeAsUnixSeconds Instant,
)
where it would serialize as
Copy code
data class Foo(
    val date: Int, // number of seconds since UNIX epoch
)
? I know I could create a custom serializer for
Foo
, but there are many classes and fields where I need this and I don't want to create custom serializers for all of them. (same question for serializing a
Duration
as an
Int
number of seconds)
Found https://github.com/Kotlin/kotlinx-datetime/issues/181 I guess something like
Copy code
val date: @Serializable(with = UnixSecondsSerializer::class) Instant,
?
h
@Serializable(with = UnixSecondsSerializer::class) val date: Instant,
c
Ah, I see
e
the annotation works on the property or the type, both result in the same serializer
as such you can also
Copy code
typealias SerializableInstant = @Serializable(with = SerializeAsUnixSeconds::class) Instant

@Serializable
data class Foo(
    val date: SerializableInstant, 
)
h
Oh, that’s nice too know πŸ‘€
c
TIL that you can typealias annotations like that
s
Also https://github.com/Kantis/ks3 might have something for your needs.
πŸ‘‹ 1
πŸ‘€ 1
e
InstantAsLong
should do the trick if you try out ks3 πŸ™‚
c
Am I right that ks3 would need to be an
api
dependency? I think serializers need to be visible on the place where serialization happens, which is most likely in downstream code
e
I can't tell for sure, I haven't tried using it that way. If you end up trying it out please let me know πŸ˜„
c
I know that it was a problem in ktmongo.opensavvy.dev: I initially implemented the serializers as
internal
but then you get weird serialization errors
s
I just checked via https://github.com/autonomousapps/dependency-analysis-gradle-plugin, and it seems to be fine with having ks3 an an implementation dependency in my project.
e
Thx for the confirmation @Sebastian Schuberth