Kotlin字段覆盖和GSON反序列化无法创建转换器类异常

时间:2018-12-30 16:26:04

标签: android serialization kotlin gson retrofit2

我在Kotlin中有一个父类,

open class Prescription(
open var name: String,
open val id: String,
open var dose: JsonElement?,
open var schedule: JsonElement?,
open var notes: String?,
@SerializedName("as_needed")
open var isAsNeeded: Boolean,
open var archiveDate: Long?) {
constructor(name: String, dose: JsonElement?, schedule: JsonElement?, isAsNeeded: Boolean, notes: String?)
    : this(
    id = name.toLowerCase() + "-" + UUID.randomUUID().toString().subSequence(0, 6),
    name = name,
    dose = dose,
    schedule = schedule,
    isAsNeeded = isAsNeeded,
    archiveDate = null,
    notes = notes
)
}

还有这样的子班

class Medication(
    override var name: String,
    override var dose: JsonElement?,
    override var schedule: JsonElement?,
    override var isAsNeeded: Boolean,
    override var notes: String?,
    override var id: String,
    val other: String?,
) : Topic, Prescription(
    name = name,
    dose = dose,
    schedule = schedule,
    isAsNeeded = isAsNeeded,
    notes = notes
)

当我尝试使用Medication反序列化GSON类时,我得到IllegalArgumentExceptionMedicationdeclares multiple JSON fields named dose.时,我不确定字段如何重复override已添加到字段。在Kotlin + GSON

中这样做的正确方法是什么

1 个答案:

答案 0 :(得分:1)

class Medication(
     name: String,
     dose: JsonElement?,
     schedule: JsonElement?,
     isAsNeeded: Boolean,
     notes: String?,
     id: String,
     val other: String?,
) : Topic, Prescription(
    name,
    dose,
    schedule,
    isAsNeeded,
    notes
)

尝试以上操作……在Medication类中,无需覆盖变量。

作为名字,     剂量,     时间表,     根据需要,     笔记 已在超类中声明,因此无需重写即可直接使用它们。

open class Prescription(
protected var name: String,
protected val id: String,
protected var dose: JsonElement?,
protected var schedule: JsonElement?,
protected var notes: String?,
@SerializedName("as_needed")
protected var isAsNeeded: Boolean,
protected var archiveDate: Long?) {
constructor(name: String, dose: JsonElement?, schedule: JsonElement?, isAsNeeded: Boolean, notes: String?)
    : this(
    id = name.toLowerCase() + "-" + UUID.randomUUID().toString().subSequence(0, 6),
    name = name,
    dose = dose,
    schedule = schedule,
    isAsNeeded = isAsNeeded,
    archiveDate = null,
    notes = notes
)
}

我相信在您的超类中保护您的var / val更可取。