首页 > 解决方案 > 命令没有价值 在 Android Kotlin 中使用 JSON

问题描述

我正在使用接收的 websocket 观察者json,并编写以下代码来反序列化 json 对象并检查它,但我让应用程序崩溃为Caused by: org.json.JSONException: No value for command

我收到的 json 对象非常简单:

{"command":"action","action":"test action"}

我的科特林代码是:

client.message.observe(this@MainActivity, androidx.lifecycle.Observer<String> { s: String? ->

   val reader = JSONObject(s)
   val action = when(reader["command"].toString()) {
                "action" -> reader["action"].toString()
                "notify" -> reader["notify"].toString()
                    else -> "Nothing"
   }
})

标签: androidjsonkotlin

解决方案


我找到了解决方案,这是由于在某些情况下没有得到正确的 json,所以首先我需要检查 json 是否包含所需的字符串,为了安全起见,我也在检查它是否不是在阅读之前清空,所以我的代码变成了:

if (s!!.isNotEmpty()) {
    reader = JSONObject(s)
    if (reader.has("command")) {
       val action = when(reader["command"].toString()) {
                    "action" -> reader["action"].toString()
                    "notify" -> reader["notify"].toString()
                    else -> "Nothing"
       }
       chaptersList.add(insertIndex, action)
       adaptor.notifyItemInserted(insertIndex)
    }
}

推荐阅读