将JSON构建为数组元素

时间:2018-12-16 00:05:26

标签: json groovy

我有这个JSON Builder Groovy代码:

let counter = (function() {
  let c = 0
  return function() {
    return c++
  }
})()

console.log(counter())
console.log(counter())
console.log(counter())

它产生如下输出:

import groovy.json.JsonBuilder
import groovy.json.JsonOutput
import groovy.json.StreamingJsonBuilder

class JSONTest {
    public static main(args) {       
        StringWriter writer = new StringWriter()
        StreamingJsonBuilder builder = new StreamingJsonBuilder(writer)
        builder.requests {
            name 'HSV Maloo'
            make 'Holden'
            year 2006
            country 'Australia'
        }
        String json = JsonOutput.prettyPrint(writer.toString())
        println json
    }
}

但是我想使用请求值作为数组元素来进行如下输出:

{
    "requests": {
        "name": "HSV Maloo",
        "make": "Holden",
        "year": 2006,
        "country": "Australia"
    }
}

如何更改输出?

1 个答案:

答案 0 :(得分:0)

您可以使用StreamingJsonBuilder DSL的形式来执行此操作,该DSL允许您传递元素名称,集合和闭包以对集合进行迭代。

def requests = [
    [name: 'HSV Maloo', make: 'Holden', year: 2006, country: 'Australia']
]

StringWriter writer = new StringWriter()
StreamingJsonBuilder builder = new StreamingJsonBuilder(writer)

builder.requests requests, { request ->
    name request.name
    make request.make
    year request.year
    country request.country
}

String json = JsonOutput.prettyPrint(writer.toString())
println json

哪个会产生:

{
    "requests": [
        {
            "name": "HSV Maloo",
            "make": "Holden",
            "year": 2006,
            "country": "Australia"
        }
    ]
}