I am trying to merge together multiple JObjects to become one single JObject. I have a list of JObjects that I am trying to iterate over and merge each of them into one object, essentially creating one large json object.
The below works fine, however when in a list it doesn't work. I know im doing something wrong but not sure what?
val obj1: JObject = RancherHelper.convertToJObject(containers.head)
val obj2: JObject = RancherHelper.convertToJObject(containers(1))
val obj3: JObject = RancherHelper.convertToJObject(containers(2))
val x: JObject = obj1 merge obj2 merge obj3
This doesn't work:
def mergeJObjects(containers: List[JObject]): JObject = {
val fullJsonObject: JObject = JObject()
val singleObject = for{
container <- containers
fullObj = fullJsonObject.merge(container)
} yield fullObj
fullJsonObject
}
答案 0 :(得分:1)
将其折叠,而不是在列表上进行映射:
site.com/myapp
您上面所写的是语法糖:
def mergeJObjects(containers: List[JObject]): JObject = {
containers.foldLeft(JObject())((merged, next) => merged.merge(next))
}
基本上,您正在容器列表上进行映射,并且将每个容器与一个空JSON对象(val fullJsonObject = JObject()
val singleObject = containers.map { container =>
val fullObj = fullJsonObject.merge(container)
fullObj
}
fullJsonObject
)合并。因此,fullJsonObject
与singleObject
没有什么不同;它是您原始JSON对象的列表。而且,由于containers
是一个不可变空的fullJsonObject
,因此您只需在方法末尾返回空的JSON对象。