0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

java.time.Instant を Serializable にする

Posted at

はじめに

こちらの記事では、kotlinx.datetime.Instant を Parcelable にする方法を書きました。今回は、java.time.Instant を Serializable にする方法を書きます。明示的に null に対応しなくていい分、こちらのほうが楽かもしれません。

実装

次のように実装します。

object InstantSerializer : KSerializer<Instant> {
  override val descriptor: SerialDescriptor
    get() = PrimitiveSerialDescriptor("Instant", PrimitiveKind.STRING)

  override fun deserialize(decoder: Decoder): Instant {
    return Instant.parse(decoder.decodeString())
  }

  override fun serialize(encoder: Encoder, value: Instant) {
    encoder.encodeString(value.toString())
  }
}

使用例

? を付けるだけで null に対応できます。

@Serializable
data class MyData(
  val instant1: @Serializable(with = InstantSerializer::class) Instant,
  val instant2: @Serializable(with = InstantSerializer::class) Instant?,
)

val input = MyData(Instant.now(), null)
val text = Json.encodeToString(input)
val output = Json.decodeFromString<MyData>(text)

println(text)   //=> {"instant1":"2021-09-12T13:48:15.956Z","instant2":null}
println(output) //=> MyData(instant1=2021-09-12T13:48:15.956Z, instant2=null)
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?