【问题标题】:Object is not abstract and does not implement abstract member对象不是抽象的,也没有实现抽象成员
【发布时间】: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


【解决方案1】:

警告是说 DateSerializer 对象需要(并且不包含)它所覆盖的对象中存在的val serialClassDesc: KSerialClassDesc

添加它以删除警告(SerialClassDescImpl 属性“日期”是您正在序列化的对象的名称 - 我相信它可以是任何字符串)

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")
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多