我有一个 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)