我尝试了这里描述的示例:http://docs.groovy-lang.org/2.4.7/html/gapi/groovy/json/JsonBuilder.html
这很好,但我如何生成json有效载荷,其中一些项目没有索引,如中的"firstElt"one_answers"secondElt">
[["firstElt","secondElt",[{"thirdElt":{"id":"1","name":"laloune"},"def":"blabla"}]]]
我尝试了以下方法:
import groovy.json.JsonBuilder;
def builder = new groovy.json.JsonBuilder()
def root = builder {
'root' 'firstElt',
'secondElt',
thirdElt(
id: '1',
name: 'laloune'
)
'def' 'blabla' }
但它会生成以下内容:
{
"thirdElt":{
"id":"1",
"name":"laloune"
},
"root":[
"firstElt",
"secondElt",
{
"id":"1",
"name":"laloune"
}
],
"def":"blabla"
}
我认为这些评论基本上回答了这个问题,但是因为我将在下面提供一个例子,有时会更清楚。
首先,您需要跟踪您的javascript数据类型。Javascript已经,除了单值事物,数组(事物列表(和对象(本质上是键值对的映射(。
在您的示例中:
[["firstElt","secondElt",[{...
^
a javascript array
[["firstElt","secondElt",[{...
^
an array within the outer array, index 0
[["firstElt","secondElt",[{...
^
a second array at index 1
[["firstElt","secondElt",[{"thirdElt":{...
^
a javascript map/object
this is the first element of the second
array in the outermost array
正如评论中提到的,通常是最简单的处理方式在groovy中,使用相关数组(groovy中的列表(和对象(groovo中的映射(布局然后将其转换为json。通过这种方式,您可以使用所有groovy构建和更改(更改(列表和地图的能力,然后只需在最后生成json即可。
生成示例中结构的示例代码:
import groovy.json.*
def structure = [ // outermost list
["firstElt", "secondElt"], // a list, structure[0]
[ // a list, structure[1]
[thirdElt: [ // a map, structure[1][0]
id: "1", // map entry, structure[1][0]['thirdElt']['id']
name: "laloune"],
def: "blabla" // map entry, structure[1][0]['def']
]
]
]
def json = JsonOutput.toJson(structure)
def pretty = JsonOutput.prettyPrint(json)
println "json: n$json"
println ""
println "pretty: n$pretty"
执行以下过程:
╭─ groovy-jsonbuilder-without-indexes
╰─➤ groovy solution.groovy
json:
[["firstElt","secondElt"],[{"thirdElt":{"id":"1","name":"laloune"},"def":"blabla"}]]
pretty:
[
[
"firstElt",
"secondElt"
],
[
{
"thirdElt": {
"id": "1",
"name": "laloune"
},
"def": "blabla"
}
]
]
╭─ groovy-jsonbuilder-without-indexes
╰─➤