grails - 在Grails中具有嵌套数组的Groovy JSONBuilder

标签 grails groovy jsonbuilder

有没有一种方法可以在Groovy中使用JSONBuilder嵌套JSON数组?更明确地说,我有一个Grails应用程序,需要渲染如下所示的内容:

{
    "event": {
        "type": "1.0",
        "templates": [
            {
                "template":{
                    "window": {
                        "type1": "id-1",
                        "type2": "id-2"
                    },
                    "object": {
                        "id-1": {
                            "type": "classA",
                            "others": [
                                {
                                    "var": "thing1",
                                    "mixed": "no"
                                }
                            ]
                        },
                        "id-2": {
                            "type": "classB",
                            "others": [
                                {
                                    "var": "thing1",
                                    "mixed": "yes"
                                }
                            ]
                        }
                    }
                }
            }
        ]
    }
}

我在让Grails Controller 使用render函数以及在服务中显式使用JSONBuilder进行构建时遇到了一些麻烦。

除了未显示"template"数组中的"template"对象外,其他所有内容似乎都可以正常工作。这是执行渲染的代码:
render(contentType: "text/json") {
    event {
        type = "1.0"
        templates = array {
            template = {
                window = {
                    type1 = "id-1"
                    type2 = "id-2"
                }
                object = {
                    "${ 'id-1' }" {
                        type = "classA"
                        others = array {
                            otherArr(var:"thing1", mixed:"yes")
                        }
                    }
                    "${ 'id-2' }" {
                        type = "classB"
                        others = array {
                            otherArr(var:"thing1", mixed:"yes")
                        }
                    }
                }
            }
        }
    }
}

最佳答案

您缺少array闭包内的级别。试试这个:

templates = array {
  item {
    template = {
      window = {
        // ...

关于grails - 在Grails中具有嵌套数组的Groovy JSONBuilder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11268012/

相关文章:

unit-testing - 如何使用Grails 2.x单元测试从i18n消息属性获取消息?

Jenkins:管道步骤中的 "Execute system groovy script"(SCM 已提交)

json - Groovy JsonBuilder 在 toString() 时的奇怪行为

json - 使用 Groovy JsonBuilder 设置委托(delegate)值

grails - 如何使用grails导出插件放置pdf的标题中心?

Grails acegi 安全约束在转发时被绕过

json - Grails 2.3 Controller 方法返回 JSON 在单元测试中返回 null

groovy invokeMethod 将方法添加到元类需要 if 语句吗?

grails - 在Cloud Foundry上运行Grails 3.0

json - Groovy 的 JsonBuilder 创建了两个额外的属性