android - Kotlin 数据类 | 添加我自己的变量而不是 JSON 键
问题描述
我正在为我的 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 对象只包含这些值,直到这里它工作正常。改造映射也在工作。
问题:
我想isPlaying
为 class添加我自己的布尔字段/变量Ticket
,稍后将在应用程序中更新。但是,此字段应默认设置为 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
}
}
推荐阅读
- c++ - find() 没有返回可以使用的 int 值,并且在编译之前给出了错误
- sql - 多个组通过保持他们的订单
- constructor - Lua中这两段代码有什么区别
- python - 如何修复 .ipynb 文件?
- html - White-space: pre 导致水平滚动, white-space: pre-wrap 导致收缩。如何结合使用两者?
- c# - 在 MVC 中刷新浏览器时如何保持控制器参数的填充?
- python - IOError:[pyAgrum] I/O 错误:流状态标志并非全部未设置
- python - H2O 框架是空的
- blazor - 异常后 Blazor 状态未更改
- android - Can't install Android emulator for IntelliJ on Windows, possibly due to path error