【发布时间】:2023-03-16 04:14:01
【问题描述】:
我有一个来自 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","version":1},"receiver_type":"client"}, 消息=}
根据上述响应,我需要将 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
}
【问题讨论】:
-
您提供的代码不起作用吗?如果没有,会发生什么?您预计会发生什么?
-
您可以对字符串
TextUtils.isEmpty(dataPay.getString("peer_connection_id"))进行简单的空检查或空检查。 -
@JensV 是的,不工作返回相同。需要返回相同的 mutablemap obj 只需一项更改就是将 KEY peer_connection_id 的 null 替换为 ""
-
@ADM 是的,如果我们解析它以在我们的 UI 上使用,我们可以检查 null 或空,但在这里我需要将此 mutablemap obj 传递给 Sendbird 库的可空函数(我用于调用)