【问题标题】:MutableList inside JSONArray in KotlinKotlin 中 JSONArray 中的 MutableList
【发布时间】:2018-08-27 05:05:41
【问题描述】:

考虑一下 Kotlin 中的这段代码:

var test = JSONArray()
test.put(mutableListOf(1, 2, 22, 15, 56))

//var test2 = ??? //sets value of test2 to 15

我到底应该在 ???让 test2 返回值 15?非常感谢!

【问题讨论】:

  • 您能否发布您要组装的 JSON?你的问题很不清楚。
  • JSONArray() 将是一个保存可变列表的,所以代码将类似于 test.put(mutableListOf(2,5, 55, 66, 77, 100)),然后是 test.put(mutableListOf(22, 15)) 和 test.put(mutableListOf(1,22, 81, 44)) 等等。可以将其视为一个 JSONArray,其中包含每个家庭中居住者的年龄。我只希望代码能够检索存储在此 JSONArray 中的第一个可变列表的第四个数字。

标签: json kotlin


【解决方案1】:

您可以执行以下操作:

val firstList = test[0] as List<Int>
val fourthElement = firstList[3] // 15

请注意,您需要在此处处理各种异常。

  • 第一个元素可能不是List&lt;Int&gt;。如果根本不是List,则初始转换将失败,如果是List 但它不包含Int 值,则读取第四个元素将导致转换异常。
  • 索引3 处的第一个列表中可能没有元素,这也可能导致异常。

【讨论】:

    【解决方案2】:

    我看到你想从 JSONArray 和 MutableList 中获取数字 15。
    我认为这会对您有所帮助:

    var mutableList = test.get(0)
    var test2 = mutableList.get(3)
    

    3 是可变列表中 15 的索引。

    【讨论】:

    • 嗨。我尝试了您的代码,但它在 var test2 = mutableList.get(3) 中给了我一个未解决的参考错误
    【解决方案3】:

    假设您使用的是org.json,最安全的方法是:

    val test = JSONArray()
    test.put(mutableListOf(1, 2, 22, 15, 56))
    
    val test2 = test.getJSONArray(0).getNumber(3)
    println(test2)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-12
      • 2021-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多