android - 命令没有价值 在 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"
}
})
解决方案
我找到了解决方案,这是由于在某些情况下没有得到正确的 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)
}
}
推荐阅读
- python - 我们可以将python包从一个环境导入到另一个环境吗
- python - 无法使用 Python 在 Windows Powershell 或 WSL Linux 终端中显示表情符号
- c - 对递归选择排序函数的混淆
- java - 在 libgdx 中找不到 BitmapFont.TextBounds
- github - 错误:没有这样的文件或目录将 env 变量传递到 Github 工作流操作中的工作目录
- jquery - 2分钟后清除本地存储
- native - 如何使 ExceptionMapper 在本机模式下工作
- java - 在 addOnItemTouchListener 中禁用 recyclerView 原生广告的 onItemClick
- angular - 如何在 html 中的表单组上关闭 angular 8 Forms 中的自动完成功能?
- python - AttributeError:“NoneType”对象没有属性“drop”