grails使用json builder构建一个数组

时间:2013-11-30 00:18:57

标签: json grails

我使用此代码构建一组员工:

render(((new JsonBuilder())
        {
            'all' employees.collect { Employee employee ->
                [
                        id: employee.id,
                        name: employee.firstName + " " + employee.lastName
                ]
            }.sort() { it.name }
        }) as JSON)

结果是:

"{
    all: [
       {id: 1, name: "balh blah"},
       ...
    ]
}"

但我想要一个没有“all”字段的数组json,如下所示:

"[
       {id: 1, name: "balh blah"},
       ...
 ]"

我怎样才能做到这一点?

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

你真的不需要JSonBuilder,如果你在集合中有你需要的东西,只需将集合作为JSON返回。

def employee = Employee.findAll()
render employee as JSON

更新: 尝试使用以下代码:

def  userList = User.list(params)
def all = userList.collect {User user ->
  [id: user.id,
  name : user.firstName + " " + user.lastName]
}.sort() { it.name }

render all as JSON