代码之家  ›  专栏  ›  技术社区  ›  Arnold Brown

如何在Kotlin中替换可变映射中特定密钥的值

  •  0
  • Arnold Brown  · 技术社区  · 5 年前

    我有一个来自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“:”, “peer_connection_id”:null },“delivery_info”:{“type”:“push”},“message_id”:“xxxx-xxxx-xxx-xx-xxxx”,“cmd”:, 消息

    根据以上响应,我需要更改的值 对等连接id 从…起 无效的 到 ""

    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
    }
    
    0 回复  |  直到 5 年前
        1
  •  0
  •   IR42    5 年前
    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
                }
            }
    }