Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Kotlin 如何使用Moshi同时解析时间戳和时区偏移?_Kotlin_Timezone Offset_Moshi_Threetenbp - Fatal编程技术网

Kotlin 如何使用Moshi同时解析时间戳和时区偏移?

Kotlin 如何使用Moshi同时解析时间戳和时区偏移?,kotlin,timezone-offset,moshi,threetenbp,Kotlin,Timezone Offset,Moshi,Threetenbp,JSON API响应包含以下属性: created_at_timestamp: 1565979486, timezone: "+01:00", 我正在使用和解析时间戳,并准备了以下自定义适配器: class ZonedDateTimeAdapter { @FromJson fun fromJson(jsonValue: Long?) = jsonValue?.let { try { ZonedDateTime.ofInstant(Ins

JSON API响应包含以下属性:

created_at_timestamp: 1565979486,
timezone: "+01:00",
我正在使用和解析时间戳,并准备了以下自定义适配器:

class ZonedDateTimeAdapter {

    @FromJson
    fun fromJson(jsonValue: Long?) = jsonValue?.let {
        try {
            ZonedDateTime.ofInstant(Instant.ofEpochSecond(jsonValue), ZoneOffset.UTC) // <---
        } catch (e: DateTimeParseException) {
            println(e.message)
            null
        }
    }

}

解析各个字段(
在时间戳处创建,
时区
)工作正常。但是,我希望摆脱硬编码的区域偏移。当解析在时间戳创建的
属性时,如何将Moshi配置为使用
时区
属性

相关的

对于在时间戳创建的
字段,您应该使用没有时区的类型。这通常是即时的。它标识了一个时刻,该时刻与解释它的时区无关


然后在封闭类型中,您可以定义一个getter方法,将instant和zone组合成一个值。
ZonedDateTime.ofInstant
方法可以做到这一点。

对于在时间戳创建的
字段,您应该使用没有时区的类型。这通常是即时的。它标识了一个时刻,该时刻与解释它的时区无关


然后在封闭类型中,您可以定义一个getter方法,将instant和zone组合成一个值。
ZoneDateTime.of Instant
方法可以做到这一点。

谢谢!这是一个完美的暗示。我根据您的建议更改了实现,对其进行了测试并更新了分支。谢谢!这是一个完美的暗示。我根据您的建议更改了实现,对其进行了测试并更新了分支。
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.Builder()
    .add(ZoneOffset::class.java, ZoneOffsetJsonAdapter())
    .add(ZonedDateTime::class.java, ZonedDateTimeJsonAdapter())
    .build()