首页 > 解决方案 > Kotlin-没有从every.eager块中获取参数的值

问题描述

我想知道如何通过覆盖现有对象上的一些键值来创建新的 jsonObject。就我而言,我有一个 jsonObjectexistingData和一个orderMap<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 上的键以及对象上该键的值是否与orderMap 条目的值不同。如果它们与对象上的键不匹配,则应使用订单映射中的值进行更新。我怎么能做到这一点,在 js 中我会使用 reduce,但我对 kotlin 不是很熟悉,而且由于我们不能在 JsonObject 上使用 fold,我想知道我该怎么做这样的事情?

标签: kotlingson

解决方案


如果我理解正确,你只想要这个:

val newObject = existingData.deepCopy().apply {
    for (key in relevantKeys) {
        add(key, Gson().toJsonTree(order[key]))
    }
}

add如果键已经存在,将覆盖旧值。toJsonTree将 转换Any?JsonElement. 这是假设里面的东西order可以在没有任何类型信息的情况下转换为 JSON。


推荐阅读