我正在为我的 andorid 应用程序使用改造和 kotlin。
对于我的一个 API,我有以下数据类
class Set(val set_id: Long, val tickets: List<Ticket>, val timer: Int) {}
class Ticket(val ticket_id: Long, val rows: List<Row>) {}
class Row(val row_id: Long, val row_numbers: List<Int>) {}
示例 JSON 数据
{
"set_id": 60942,
"tickets": [
{
"ticket_id": 304706,
"rows": [
{
"row_id": 914116,
"row_numbers": [
0,
11,
21,
0,
42,
52,
0,
76,
85
]
}
]
}
],
"timer": 12
}
Set
类包含一个 Ticket
列表,每个票都有一个 Row
列表
我的 JSON 对象仅包含这些值,并且到这里为止工作正常。改造映射也有效。
问题:
我想为类 Ticket
添加我自己的 bool 字段/变量 isPlaying
,稍后将在应用程序中更新。但是,这个字段应该默认设置为 true。
我试过了
class Ticket(val ticket_id: Long, val rows: List<Row>, var isPlaying: Boolean = true) {}
还有这个
class Ticket(val ticket_id: Long, val rows: List<Row>) {
var isPlaying: Boolean = true
}
注意:JSON 没有 isPlaying
键,我只希望它用于应用程序逻辑。
两者均无效,isPlaying
始终显示 false
。我希望它默认为 true
。
请帮帮我。谢谢!
最佳答案
在对象被改造实例化的情况下,由于下面使用的解析库,默认参数在数据类中不起作用,这可能会在不调用构造函数的情况下创建对象。例如 Gson
使用 sun.misc.Unsafe
创建对象。
您可以做的 - 为具有默认值的字段添加支持属性:
class Ticket(
val ticket_id: Long,
val rows: List<Row>,
private var _isPlaying: Boolean? = true
) {
var isPlaying
get() = _isPlaying ?: true
set(value) {
_isPlaying = value
}
}
关于android - Kotlin 数据类 |添加我自己的变量而不是 JSON 键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50522602/