我在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
类时,我得到IllegalArgumentException
说Medication
类declares multiple JSON fields named dose.
时,我不确定字段如何重复override
已添加到字段。在Kotlin
+ GSON
答案 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更可取。