【发布时间】:2018-08-05 03:22:39
【问题描述】:
我正在尝试使用 Kotlin 的序列化实现自定义序列化程序。 当我将示例代码粘贴到 Android Studio 3.1.3 中时,我收到一条警告:
Object DateSerializer is not abstract and does not implement abstract member
public abstract val serialClassDesc: KSerialClassDesc defined in kotlinx.serialization.KSerializer
我使用的代码是:
import kotlinx.serialization.*
import kotlinx.serialization.json.JSON
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.*
@Serializer(forClass = Date::class)
object DateSerializer : KSerializer<Date> {
private val df: DateFormat = SimpleDateFormat("dd/MM/yyyy HH:mm:ss.SSS")
override fun save(output: KOutput, obj: Date) {
output.writeStringValue(df.format(obj))
}
override fun load(input: KInput): Date {
return df.parse(input.readStringValue())
}
}
示例来源:https://github.com/Kotlin/kotlinx.serialization/example-jvm/src/WithDemo.kt
我假设这个例子是正确的 - 我做错了什么?
【问题讨论】:
-
我建议你避免使用
SimpleDateFormat类。它不仅过时了,而且出了名的麻烦。今天我们在java.time, the modern Java date and time API 中做得更好。同样对于序列化为什么不坚持ISO 8601 format? java.time 类无需任何显式格式化程序即可读取和写入此格式。 -
听起来不错的建议 :) 我在这里没有这样做,因为这是 Kotlin.Serialization 提供的示例。我修复了警告并将其添加到此处,因为我在 StackOverflow 或谷歌搜索中找不到答案。
标签: kotlin serialization