我有这个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,我错过了什么?
1条答案
按热度按时间nxowjjhe1#
createdAt
属性可能被设置为null,因为您正在将JSON反序列化为这个类,而反序列化器无法在JSON中找到“createdAt”键,所以它只是将null传递给构造函数。如果你只是想创建一个从另一个属性计算的属性,你可以写一个getter:
请注意,我将新属性命名为
creationZonedDateTime
,使其与created_at
更有区别。为了保持一致,我还建议将created_at
重命名为camel case。当然,这需要您以某种方式指定其JSON键名称,具体取决于您使用的库。由于每次访问属性时getter都会导致创建一个新的
ZonedDateTime
,因此您也可以将其改为延迟计算: