Kotlin中如何替换MutableMap内指定KEY对应的VALUE(附场景实例)
替换API返回响应中指定KEY对应值的实现优化
原始响应数据类型为 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"},
message=}
需求为将上述响应中 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","") } } } }
原代码可优化点
- 多层if嵌套结构冗余,可读性差,后续如果JSON层级结构变动,维护成本很高
- 直接调用
getString("peer_connection_id")读取null值时,多数JSON解析库会直接抛出类型异常,存在崩溃风险 - 判空写法不严谨,
equals(null)的写法本身就有触发空指针的可能
优化后实现方案
private fun replacePeerID(receivedMap: Map<String, String>): Map<String, String> { val msgData = JSONObject(receivedMap["sendbird_call"]) msgData.optJSONObject("command") ?.optJSONObject("payload") ?.let { payload -> if (payload.has("peer_connection_id") && payload.opt("peer_connection_id") == null) { payload.put("peer_connection_id", "") } } // 补充修改后数据回写逻辑,避免只修改JSONObject未同步到Map的问题 if (receivedMap is MutableMap) { receivedMap["sendbird_call"] = msgData.toString() } return receivedMap }
优化说明
- 用
optJSONObject替代getJSONObject+has()判断逻辑,结合Kotlin空安全调用符?.自动处理节点不存在的场景,完全消除多层嵌套 - 用
opt("peer_connection_id")读取字段值,即使字段为null也不会抛出异常,判空逻辑更安全 - 补充了修改后的JSON数据回写Map的逻辑,解决了原有参考实现修改不生效的问题
内容的提问来源于stack exchange,提问作者Arnold Brown
相关产品推荐
相关产品推荐

