2
看起來很簡單的事情,也許在Jerkson中有例程,但我寫了一個簡單的合併函數。它應該合併兩個合併字典的JSON樹,並使用更新值覆蓋源和更新中的任何內容,並且更新不在源中的任何內容。我想這是你想要合併的個人選擇,所以我可以看到這裏沒有內置的內容。我想驗證有沒有更好的方法,這種方式並不愚蠢。在Scala中使用Jerkson合併兩個JSON樹
def merge(name: String, source: JObject, update: JObject) : JField = {
JField(name, JObject(
source.fields.map { x: JField =>
// Do we have an updated value in our update
findValue(x.name, update) match {
// If so check what kind of value
case Some(updatedField) => updatedField match {
// If it's an object, merge it down
case updatedObject: JObject => {
x.value match {
case sourceObject: JObject => merge(x.name, sourceObject, updatedObject)
case other => JField(x.name, updatedObject)
}
}
case other => other
}
case None => x
}
}
// Concat with a list of fields that exist in the update and not in the source
::: (update.fields.filter { x =>
findValue(x.name, source) match {
case None => true
case Some() => false
}
})
))
}
def findValue(name: String, obj: JObject) : Option[JField] = obj.fields.filter(_.name==name).headOption