kotlin - Kotlin-没有从every.eager块中获取参数的值
问题描述
我想知道如何通过覆盖现有对象上的一些键值来创建新的 jsonObject。就我而言,我有一个 jsonObjectexistingData
和一个order
Map<String, Any> 类型。
// order is of type Map<String, Any?>
val keys = listOf("service", "customerContact", "deliveryAddress", "deliveryZipCode", "deliveryZipArea", "deliveryCountryCode", "deliveryPhoneNumber")
val newObject = existingData
.toMap()
.foldLeft(jsonObject()) { acc, entry ->
if (relevantKeys.contains(entry.key)
&& !matching(entry.value, order.get(entry.key))
) acc.set(entry.key, order?.get(entry.key).toString())
else acc.set(entry.key, entry.value.asString)
}
因此,在这里我需要检查keys
列表是否包含 jsonObject 上的键以及对象上该键的值是否与order
Map 条目的值不同。如果它们与对象上的键不匹配,则应使用订单映射中的值进行更新。我怎么能做到这一点,在 js 中我会使用 reduce,但我对 kotlin 不是很熟悉,而且由于我们不能在 JsonObject 上使用 fold,我想知道我该怎么做这样的事情?
解决方案
如果我理解正确,你只想要这个:
val newObject = existingData.deepCopy().apply {
for (key in relevantKeys) {
add(key, Gson().toJsonTree(order[key]))
}
}
add
如果键已经存在,将覆盖旧值。toJsonTree
将 转换Any?
为JsonElement
. 这是假设里面的东西order
可以在没有任何类型信息的情况下转换为 JSON。
推荐阅读
- python - “conda 更新 conda”与“conda 更新 --all”
- ios - 无法从 App Store 获取待售产品
- spring-boot - SpringJUnit4ClassRunner 测试的配置与 SpringBootTest 冲突
- jasper-reports - Jasperreports:如何设置轴间隔?
- visual-studio-code - 使用特定节点版本运行 git pre-commit hook
- android - 如何通过appium在移动应用中点击图片
- firebase - Firebase Analytics,规定的事件参数是否也算作自定义参数?
- oracle - 如何在 where 条件下使用 app_user
- python - 如何将 API 响应转换为 JSON 对象?
- azure - Azure 策略将额外资源报告为不合规