hey*_*hey 6 android gradle kotlin moshi
我有一个 Android 应用程序,我正在尝试通过脱糖从 ThreeTenABP 过渡到Android Gradle Plugin 4.0支持的 Java 8“时间”API
这是我的自定义 Moshi 适配器
@Keep
internal class DateTimeAdapter {
@ToJson fun toJson(@DateTimeTimestamp dateTime: LocalDateTime): Long {
return dateTime.toEpochSecond(ZoneOffset.UTC)
}
@FromJson @DateTimeTimestamp fun fromJson(dateTimeTimestamp: Long): LocalDateTime {
return localDateTimeOf(dateTimeTimestamp)
}
}
@JsonQualifier
@Retention(AnnotationRetention.RUNTIME)
internal annotation class DateTimeTimestamp
Run Code Online (Sandbox Code Playgroud)
这是我在构建 Moshi 实例时提供它的方式
fun provideMoshi(): Moshi {
return Moshi.Builder()
.add(DateTimeAdapter())
.add(KotlinJsonAdapterFactory()).build()
}
Run Code Online (Sandbox Code Playgroud)
这是我在我的一个 DTO 中使用它的方式
@Keep
data class ErrorDto(
@Json(name = "timestamp") @DateTimeTimestamp val date: LocalDateTime?,
@Json(name = "status") val statusCode: Int,
)
Run Code Online (Sandbox Code Playgroud)
但是,在运行时,我收到此异常
java.lang.IllegalArgumentException: Platform class java.time.LocalDateTime requires explicit JsonAdapter to be registered
Run Code Online (Sandbox Code Playgroud)
完全相同的适配器适用于 org.threeten.bp.LocalDateTime。即应用不崩溃,Long时间戳成功转为LocalDateTime
| 归档时间: |
|
| 查看次数: |
420 次 |
| 最近记录: |