0

我尝试了这里描述的示例:http ://docs.groovy-lang.org/2.4.7/html/gapi/groovy/json/JsonBuilder.html

这很好用,但是我如何生成一个 json 有效负载,其中某些项目没有索引,例如“firstElt”和“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"
}
4

1 回答 1

1

我认为评论基本上回答了这个问题,但有时通过一个例子更清楚,我将在下面提供一个。

首先,您需要跟踪您的 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 中的列表)和对象(groovy 中的映射)布局生成一个 groovy 数据结构,然后将其转换为 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
╰─➤
于 2019-11-18T09:01:57.583 回答