参考这个问题的解决方案: - Building JSON using JsonBuilder
def json = new groovy.json.JsonBuilder()
json {
isOut false
baleRun {
incData true
appendCricket( [
{
min 10
max 32
price "10000"
}
])
}
}
println json.toPrettyString()
输出: -
{
"isOut": false,
"baleRun": {
"incData": true,
"appendCricket": [
{
"min": 10,
"max": 32,
"price": "10000"
}
]
}
}
不需要外部花括号(在我的情况下)
我有另一个JSON,我需要插入新创建的JSON: -
def newJSON = '''{
"count": 6,
"max": "1",
"bale": false,
"cricketDetails": {
"cricketCategory": [
{
"ball": 16,
"swing": true,
"code": "2",
"umpireStatus": [
{
"code": "TYUR",
"avail": 0,
"position": 1,
"request": ""
},
{
"code": "TGRE",
"avail": 0,
"position": 2,
"request": ""
}
],
"min": "0",
"extraCover": 12,
"price": "DNR",
"program": "1 Day"
}
]
},
"fourRuns": 4,
"sixRuns": 6
}'''
我在下面的代码中尝试将JSON1(使用JsonBuilder创建)添加到特定位置的JSON2(我需要插入): -
newJson.cricketDetails.cricketCategory.getAt(0).json = json
我需要的实际输出: -
{
"count": 6,
"max": "1",
"bale": false,
"cricketDetails": {
"cricketCategory": [{
"ball": 16,
"swing": true,
"code": "2",
"umpireStatus": [{
"code": "TYUR",
"avail": 0,
"position": 1,
"request": ""
},
{
"code": "TGRE",
"avail": 0,
"position": 2,
"request": ""
}],
"isOut": false,
"baleRun": {
"incData": true,
"appendCricket": [{
"min": 10,
"max": 32,
"price": "10000"
}]
},
"min": "0",
"extraCover": 12,
"price": "DNR",
"program": "1 Day"
}]
},
"fourRuns": 4,
"sixRuns": 6
}
我怎样才能做到这一点?此外,如果我尝试上面提到的代码,每次使用" json"添加外部花括号。作为关键。你可以从我的输出中看到,我不需要和键在这里。
答案 0 :(得分:2)
newJSON 是字符串。 json 是JsonBuilder的实例,它具有getContent方法,它将json作为map返回。
首先,您需要将newJSON解析为map。
然后您可以轻松地将一张地图插入其他地图。
最后从这张地图中生成json作为字符串。
def parsedJson = new JsonSlurper().parseText(newJSON) // parse to map
parsedJson.cricketDetails.cricketCategory.getAt(0) << json.content // modify map
def out = new JsonOutput()
println out.prettyPrint(out.toJson(parsedJson)) //output final json