我试图在Groovy中生成以下JSON结构,但没有得到我想要的输出。
{
"settings": [
{
"location": "remote",
"stance": "cold"
},
{
"spareParts": {
"id": "123" {
"info": "In stock"
}
}
}
]
}
答案 0 :(得分:4)
首先,目前问题中的JSON无效。 :)其次,既然Groovy对此有很大的支持,那就不需要丑陋了。 :)
您可以使用闭包,地图或组合,请参阅此示例:https://github.com/jonatan-ivanov/groovy-training/blob/master/examples/050_JsonBuilder.groovy
以下是使用地图的(我认为)JSON的示例:
builder = new groovy.json.JsonBuilder(
settings: [
[
location: 'remote',
stance: 'cold'
],
[
spareparts: [
id: '123',
info: 'In stock'
]
]
]
)
println builder.toPrettyString()
这是它的输出:
{
"settings": [
{
"location": "remote",
"stance": "cold"
},
{
"spareparts": {
"id": "123",
"info": "In stock"
}
}
]
}
答案 1 :(得分:1)
我会为此使用地图和列表的组合。考虑更简单的情况:
import groovy.json.JsonBuilder
def map = [:]
def map1 = [:]
map1['location'] = 'remote'
def list = []
list << ['id' : '123', 'info' : 'In stock']
map1['spareParts'] = list
map['settings'] = [map1]
def jsonBuilder = new JsonBuilder(map)
println jsonBuilder.toPrettyString()
然后是更复杂的情况(这应该重构):
import groovy.json.JsonBuilder
def map = [:]
def map1 = [:]
map1['location'] = 'remote'
def list1 = []
list1 << ['id' : '123', 'info' : 'In stock']
map1['spareParts'] = list1
map['settings'] = map1
def map2 = [:]
map2['location'] = 'local'
def list2 = []
list2 << ['id' : '505', 'info' : 'none']
map2['spareParts'] = list2
map['settings'] = [map1, map2]
def jsonBuilder = new JsonBuilder(map)
println jsonBuilder.toPrettyString()