如何在 Kotlin 的可变映射中替换特定 KEY 的 VALUE

How to replace a VALUE of Particular KEY inside Mutable Map in Kotlin

提问人:Arnold Brown 提问时间:10/5/2021 最后编辑:Arnold Brown 更新时间:10/5/2021 访问量:582

问:

我有来自 api 的响应,我想替换特定 KEY 的 VALUE。怎么做

MutableMap<String!, String!> 

{sendbird_call={“user_id”:“919900000000”,“push_sound”:“默认”,“is_voip”:true,“push_alert”:“”,“client_id”:“xxxxx-xxx-xxxx-xxxx-xxxxxxx”,“command”:{“sequence_number”:2,“payload”:{“sdp”:“sdpppppp”,“call_id”:“xxxx-xxx-xxx-xxx-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
}
人造人 科特林 可变

评论

1赞 JensV 10/5/2021
您提供的代码不起作用吗?如果没有,会发生什么,你期望会发生什么?
0赞 ADM 10/5/2021
您可以在 String 上放置一个简单的 null 检查或空检查。TextUtils.isEmpty(dataPay.getString("peer_connection_id"))
0赞 Arnold Brown 10/5/2021
@JensV 是的,不工作,返回相同。只需进行一次更改即可返回相同的可变映射 obj 是将 KEY peer_connection_id 的 null 替换为 “”
0赞 Arnold Brown 10/5/2021
@ADM是的,如果我们解析它以在我们的 UI 上使用,我们可以检查 null 或空,但在这里我需要将这个可变映射 obj 传递给 Sendbird 库的可为 null 函数(我用于调用)

答:

0赞 IR42 10/5/2021 #1
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
            }
        }
}

评论

0赞 Arnold Brown 10/5/2021
如何将其形成一个函数,在替换后返回为可变映射?我已经用你的答案编辑了我的问题。
0赞 Arnold Brown 10/5/2021
java.lang.IllegalArgumentException:指定为 non-null 的参数为 null:方法 kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull,参数 peerConnectionId