首页 > 解决方案 > 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默认的。

请帮帮我。谢谢!

标签: androidjsonkotlingsonretrofit2

解决方案


由于下面使用的解析库,当对象通过改造实例化时,默认参数在数据类中不起作用,这可能会在不调用构造函数的情况下创建对象。例如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
        }
}

推荐阅读