我正在尝试使用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
我认为示例是正确的-我在做什么错了?
答案 0 :(得分:0)
警告是说DateSerializer对象需要(并且不包含)要覆盖的对象中存在的val serialClassDesc: KSerialClassDesc
。
添加它以消除警告(SerialClassDescImpl属性“ Date”是您要序列化的对象的名称-我相信它可以是任何字符串)
import kotlinx.serialization.*
import kotlinx.serialization.json.JSON
import kotlinx.serialization.internal.SerialClassDescImpl
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())
}
override val serialClassDesc: KSerialClassDesc = SerialClassDescImpl("Date")
}