首页 > 解决方案 > 从 groovy 合并两个 JSON

问题描述

我有 2 个 JSON 文件,我想合并这 2 个文件并使用 groovy 创建一个 JSON 消息。基于“类型”值,我将合并这两个 JSON 文件。

输入 JSON 消息1

{"message":[{"name":"HelloFile","type": "input"},{"name":"SecondFile","type": "error"}]

输入 JSON 消息2

[{"name":"NewFile","type": "input"},{"name":"MyFile","type": "output"}]

预期的 JSON

{"message":[{"name":"NewFile","type": "input"},{"name":"MyFile","type": "output"},{"name":"SecondFile","type": "error"}]}

我使用了下面的常规代码。

JsonBuilder jsonBuilder = new JsonBuilder(JSON1)
jsonBuilder.content.message= JSON2
def updatedBody = jsonBuilder.toString()

从上面的代码中,我得到了以下消息。

{"message":[{"name":"NewFile","type": "input"},{"name":"MyFile","type": "output"}]}

对此进行排序的任何帮助将不胜感激。

标签: jsongroovy

解决方案


尝试使用 JsonSlurper:

import groovy.json.*

​def json1 = '{"message":[{"name":"HelloFile","type": "input"},{"name":"SecondFile","type": "error"}]}'​​​​​​​​​​​​​
def json2 = '[{"name":"NewFile","type": "input"},{"name":"MyFile","type": "output"}]'
def slurper = new JsonSlurper()
def json1Obj = slurper.parseText(json1)
def json2Obj = slurper.parseText(json2)
json1Obj.message+=json2Obj
println JsonOutput.toJson​(json1Obj)​

这打印:

{"message":[{"name":"HelloFile","type":"input"},{"name":"SecondFile","type":"error"},{"name":"NewFile","type":"input"},{"name":"MyFile","type":"output"}]}

推荐阅读