How to use groovy builder to generate an array-type json?

放肆的年华 提交于 2019-11-30 11:46:58

The syntax you propose doesn't look possible, as I don't believe it's valid groovy. A closure such as {"blah":"foo"} doesn't makes sense to groovy, and you're going to be constrained by syntactical limitations. I think the best you're going to be able to do is something within the following:

def root = builder.call (
   [
      {
        code "111"
        value "222"
      },
      {code "222"; value "444"}, //note these are statements within a closure, so ';' separates instead of ',', and no ':' used
      [code: "333", value:"555"], //map also allowed
      [1,5,7]                     //as are nested lists
   ]
)

it is also possible to create list of closures and pass it to builder

import groovy.json.*

dataList = [
    [a:3, b:4],
    [a:43, b:3, c:32]
]
builder = new JsonBuilder()
builder {
    items dataList.collect {data ->
        return {
            my_new_key ''
            data.each {key, value ->
                "$key" value
            }
        }
    }
}
println builder.toPrettyString()

I like conversion in the end more than builder,

def json = [ 
            profile: [
                      _id: profile._id,
                      fullName: profile.fullName,
                      picture: profile.picture
                     ]
            ,title: title
            ,details: details
            ,tags: ["tag1","tag2"]
            ,internalTags: ["test"]
            ,taggedProfiles: []
           ] as JSON
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!