android - 如何在 Kotlin 的可变映射中替换特定键的值
问题描述
我有来自 api 的响应,我想替换特定 KEY 的 VALUE。怎么做
MutableMap<String!, String!>
{sendbird_call={"user_id":"91990000000","push_sound":"default","is_voip":true,"push_alert":"","client_id":"xxxxx-xxx-xxxx-xxxx-xxxxxxx"," command":{"sequence_number":2,"payload":{"sdp":"sdpppppp","call_id":"xxxx-xxx-xxx-xxxx-xxxxxx", "peer_connection_id":null },"delivery_info": {"type":"push"},"message_id":"xxxx-xxxx-xxx-xx-xxxx","cmd":"SGNL","type":"offer","call_type":"direct_call", “版本”:1},“接收者类型”:“客户端”},消息=}
从上面的响应中,我需要将peer_connection_id的值从null更改为""
var msgData = JSONObject(receivedMap["sendbird_call"])
if (msgData.has("command")) {
val dataCommand: JSONObject = msgData.getJSONObject("command")
if (dataCommand.has("payload")) {
val dataPay: JSONObject = dataCommand.getJSONObject("payload")
if (dataPay.has("peer_connection_id")) {
if(dataPay.getString("peer_connection_id").equals(null)){
dataPay.put("peer_connection_id","")
}
}
}
}
任何建议或帮助
IR42的回答
private fun replacePeerID(receivedMap: Map<String, String>): Map<String, String> {
var msgData = JSONObject(receivedMap["sendbird_call"])
msgData.optJSONObject("command")
?.optJSONObject("payload")
?.let {
if (it.has("peer_connection_id") && it.opt("peer_connection_id") == null) {
it.put("peer_connection_id", "")
}
}
return receivedMap
}
解决方案
private fun replacePeerID(receivedMap: Map<String, String>): Map<String, String> {
val msgData = JSONObject(receivedMap["sendbird_call"] ?: "{}")
return msgData.optJSONObject("command")
?.optJSONObject("payload")
.let { payloadObject ->
if (payloadObject != null &&
payloadObject.has("peer_connection_id") &&
payloadObject.opt("peer_connection_id") == JSONObject.NULL
) {
payloadObject.put("peer_connection_id", "")
receivedMap + ("sendbird_call" to msgData.toString())
} else {
receivedMap
}
}
}
推荐阅读
- html - Photoshop 字体与浏览器字体系列相比看起来不同
- python - 如何使用 xml.etree 获取元素的 xpath
- sql - 日期/时间范围内的模式序列
- angular - 提交成功时如何重置字段
- r - 通过循环字符串在ggplot中设置x变量
- npm - Webpack 可以用 coffee-loader 构建 Vue 模板吗?
- haskell - 如何转置二维向量
- pandas - 删除行:与其他列不匹配
- jquery - Html 5 Audio 在 iphone safari 浏览器中不起作用
- python - 如何从 pandas 数据框中取出值并将它们放入一个 numpy 数组中?