Merging multiple JObjects in a list - Json4s

时间:2018-09-18 20:08:55

标签: java json scala list

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
}

1 个答案:

答案 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 )合并。因此,fullJsonObjectsingleObject没有什么不同;它是您原始JSON对象的列表。而且,由于containers是一个不可变空的fullJsonObject,因此您只需在方法末尾返回空的JSON对象。