kotlin - 如何与 Moshi 同时解析时间戳和时区偏移量?
问题描述
JSON-API 响应包含以下属性:
created_at_timestamp: 1565979486,
timezone: "+01:00",
我正在使用Moshi和ThreeTenBp来解析时间戳并准备了以下自定义适配器:
class ZonedDateTimeAdapter {
@FromJson
fun fromJson(jsonValue: Long?) = jsonValue?.let {
try {
ZonedDateTime.ofInstant(Instant.ofEpochSecond(jsonValue), ZoneOffset.UTC) // <---
} catch (e: DateTimeParseException) {
println(e.message)
null
}
}
}
如您所见,区域偏移量在这里是硬编码的。
class ZonedDateTimeJsonAdapter : JsonAdapter<ZonedDateTime>() {
private val delegate = ZonedDateTimeAdapter()
override fun fromJson(reader: JsonReader): ZonedDateTime? {
val jsonValue = reader.nextLong()
return delegate.fromJson(jsonValue)
}
}
...
class ZoneOffsetAdapter {
@FromJson
fun fromJson(jsonValue: String?) = jsonValue?.let {
try {
ZoneOffset.of(jsonValue)
} catch (e: DateTimeException) {
println(e.message)
null
}
}
}
...
class ZoneOffsetJsonAdapter : JsonAdapter<ZoneOffset>() {
private val delegate = ZoneOffsetAdapter()
override fun fromJson(reader: JsonReader): ZoneOffset? {
val jsonValue = reader.nextString()
return delegate.fromJson(jsonValue)
}
}
适配器注册Moshi
如下:
Moshi.Builder()
.add(ZoneOffset::class.java, ZoneOffsetJsonAdapter())
.add(ZonedDateTime::class.java, ZonedDateTimeJsonAdapter())
.build()
解析各个字段 ( created_at_timestamp
, timezone
) 工作正常。但是,我想摆脱硬编码的区域偏移量。timezone
在解析属性时,如何配置 Moshi 以依赖该created_at_timestamp
属性。
有关的
解决方案
对于该created_at_timestamp
字段,您应该使用没有时区的类型。这通常是Instant
. 它识别一个时刻,与它被解释的时区无关。
然后在您的封闭类型中,您可以定义一个 getter 方法将即时和区域组合为一个值。该ZonedDateTime.ofInstant
方法可以做到这一点。
推荐阅读
- wix - 为 Wix / Windows Installer 安装的文件指定权限时如何包含继承权限?
- immutable.js - 如何使用 immutable.js 设置带有条件的变量
- python-3.x - 处理用于计算 SVD 的大型非稀疏矩阵
- java - AWS Lambda 和 Java 反射 (Guava)
- excel - 如果单元格包含特定缩进,则 VBA 代码移动单元格
- angular - Angular 7 - 解析器 API 和分页器逻辑?
- powershell - 从 2 个变量中导出匹配结果
- excel - 如何使用数字列 VBA 从范围中添加数据验证
- php - 访问数据库以使用预填充的下拉列表或自定义选项 php html jquery sql 数据表创建列表
- alfresco - 基于 Alfresco 共享表单的关联 - 节点选择