Merging Two JSON Documents Using Jackson

前端 未结 6 2248
有刺的猬
有刺的猬 2020-11-29 22:51

Is it possible to merge two JSON documents with the Jackson JSON library? I am basically using the Jackson mapper with simple Java Maps.

I\'ve tried to search in Goo

6条回答
  •  青春惊慌失措
    2020-11-29 23:47

    Below is an implementation in Scala. The source and target node are mostly commutative except when a branch exists in both source and target.

      def mergeYamlObjects(source: ObjectNode, target: ObjectNode, overwrite: Boolean = true): ObjectNode = {
        if (target == null)
          source
        else if (source == null)
          target
        else {
          val result = source.deepCopy
          val fieldlist = source.fieldNames.asScala.toList ++ target.fieldNames.asScala.toList
          for (item <- fieldlist) {
            if (!(source has item)) {
              result put(item, target get item)
            } else {
              if ((source get item).isValueNode) {
                if (target has item)
                  if (overwrite)
                    result.put(item, target get item)
              } else {
                result.put(item, mergeYamlObjects(source.get(item).asInstanceOf[ObjectNode],
                  target.get(item).asInstanceOf[ObjectNode], overwrite = overwrite))
              }
            }
          }
          result
        }
      }
    

提交回复
热议问题