如何在 groovy 中使用 JsonBuilder 创建数组

pix*_*xel 4 arrays groovy json jsonbuilder

我想使用闭包方式来制作以下 json:

{
    "root": [
        {
            "key": "testkey",
            "value": "testvalue"
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

我正在使用以下语法:

new JsonBuilder().root {
        'key'(testKey)
        'value'(testValue)
}
Run Code Online (Sandbox Code Playgroud)

但它产生:

{
    "root": {
        "key": "testkey",
        "value": "testvalue"
    }
}
Run Code Online (Sandbox Code Playgroud)

Rao*_*Rao 5

你可以写如下:

def json = new groovy.json.JsonBuilder()
json  { 
  root (
   [
       {
        key ('color')
        value ('orange')
     }
   ]
  )
}

println json.toPrettyString()
Run Code Online (Sandbox Code Playgroud)

注意root上面的数组是如何传递的。


Szy*_*iak 4

您的示例可以正常工作,因为您传递了一个简单的键映射root。您必须传递一个列表,而不是产生预期的输出。考虑以下示例:

import groovy.json.JsonBuilder

def builder = new JsonBuilder()
builder {
    root((1..3).collect { [key: "Key for ${it}", value: "Value for ${it}"] })
}

println builder.toPrettyString()
Run Code Online (Sandbox Code Playgroud)

在此示例中,我们将使用创建的元素列表传递(1..3).collect {}root节点。我们必须将初始化与构建 JSON 主体分开,因为new JsonBuilder().root([])甚至builder.root([])会抛出异常,因为没有方法需要类型为 的参数Listroot在闭包内定义节点列表可以解决这个问题。

输出

{
    "root": [
        {
            "key": "Key for 1",
            "value": "Value for 1"
        },
        {
            "key": "Key for 2",
            "value": "Value for 2"
        },
        {
            "key": "Key for 3",
            "value": "Value for 3"
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)