在Kotlin中将时间戳转换为Java 8 API ZonedDateTime

lokaqttq  于 2023-03-24  发布在  Kotlin
关注(0)|答案(1)|浏览(206)

我有这个json:

{
    "name": "Hungarian Translation",
    "language": "hu",
    "created_at": 1676618826043,
  }

并希望将其转换为Kotlin数据类:

data class TranslationBook(
    val name: String,
    val language: String,
    val created_at: Long,
    val createdAt: ZonedDateTime? =
        ZonedDateTime.ofInstant(Instant.ofEpochMilli(created_at), ZoneId.of("Asia/Jakarta")),
) : Parcelable

也就是说我想把created_attimestamp保存为createdAt属性中的ZonedDateTime,但是createdAt属性一直为null,我错过了什么?

nxowjjhe

nxowjjhe1#

createdAt属性可能被设置为null,因为您正在将JSON反序列化为这个类,而反序列化器无法在JSON中找到“createdAt”键,所以它只是将null传递给构造函数。
如果你只是想创建一个从另一个属性计算的属性,你可以写一个getter:

val creationZonedDateTime: ZonedDateTime
    get() = ZonedDateTime.ofInstant(Instant.ofEpochMilli(created_at), ZoneId.of("Asia/Jakarta"))

请注意,我将新属性命名为creationZonedDateTime,使其与created_at更有区别。为了保持一致,我还建议将created_at重命名为camel case。当然,这需要您以某种方式指定其JSON键名称,具体取决于您使用的库。
由于每次访问属性时getter都会导致创建一个新的ZonedDateTime,因此您也可以将其改为延迟计算:

val creationZonedDateTime: ZonedDateTime by lazy {
    ZonedDateTime.ofInstant(Instant.ofEpochMilli(created_at), ZoneId.of("Asia/Jakarta"))
}

相关问题