android - Kotlin 数据类 |添加我自己的变量而不是 JSON 键

标签 android json kotlin gson retrofit2

我正在为我的 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/

相关文章:

android - 类型不匹配 : inferred type is but was expected

android - 单元测试作用域 View 模型的最佳方法

android - 在测试应用程序时使用释放 key ?

javascript - 如果使用 Select2 YII2 选择第一个字段,则自动填充下面的字段

php - 用户在 JavaScript 中提供的数组名称

kotlin - 将协程上下文显式传递给异步调用与将其安装在封闭范围内会产生不同的异常处理行为

java - C服务器未接收java/android客户端消息

javascript - 如何格式化路径以便在 Express.JS 中接收通用 JSON 对象?

android - 如何在 OnCompleteListener Firebase 中使用 Async/Await/Coroutines

import - Kotlin.math 包未导入