我有一个Android应用程序,我正在尝试从ThreeTenABP过渡到Android Gradle Plugin 4.0 through desugaring支持的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
这是我在构建Moshi实例时提供它的方式
fun provideMoshi(): Moshi {
return Moshi.Builder()
.add(DateTimeAdapter())
.add(KotlinJsonAdapterFactory()).build()
}
这是我在我的一个DTO中使用它的方式
@Keep
data class ErrorDto(
@Json(name = "timestamp") @DateTimeTimestamp val date: LocalDateTime?,
@Json(name = "status") val statusCode: Int,
)
但是,在运行时,出现此异常
java.lang.IllegalArgumentException: Platform class java.time.LocalDateTime requires explicit JsonAdapter to be registered
相同的完全适配器可以与org.threeten.bp.LocalDateTime一起正常工作。也就是说,应用程序不会崩溃,并且Long时间戳已成功转换为LocalDateTime