首页 > 解决方案 > 如何与 Moshi 同时解析时间戳和时区偏移量?

问题描述

JSON-API 响应包含以下属性:

created_at_timestamp: 1565979486,
timezone: "+01:00",

我正在使用MoshiThreeTenBp来解析时间戳并准备了以下自定义适配器:

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属性。

有关的

标签: kotlintimezone-offsetmoshithreetenbp

解决方案


对于该created_at_timestamp字段,您应该使用没有时区的类型。这通常是Instant. 它识别一个时刻,与它被解释的时区无关。

然后在您的封闭类型中,您可以定义一个 getter 方法将即时和区域组合为一个值。该ZonedDateTime.ofInstant方法可以做到这一点。


推荐阅读