【问题标题】:Groovy JSONBuilder with Nested Array in Grails在 Grails 中使用嵌套数组的 Groovy JSONBuilder
【发布时间】:2012-06-29 19:43:19
【问题描述】:

有没有办法在 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 控制器使用 render 函数以及在服务中显式使用 JSONBuilder 来构建它时遇到了一些问题。

除了“模板”数组中的“模板”对象没有被渲染之外,一切似乎都正常。这是进行渲染的代码:

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")
                        }
                    }
                }
            }
        }
    }
}

【问题讨论】:

    标签: grails groovy jsonbuilder


    【解决方案1】:

    array 闭包中缺少一个级别。试试这个:

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

    【讨论】:

    • 这似乎对我不起作用。我收到以下错误消息:Misplaced key: expected mode of KEY but was OBJECT. Stacktrace follows: Message: Misplaced key: expected mode of KEY but was OBJECT Line | Method ->> 199 | value in grails.converters.JSON
    • 对不起,我的错误。我最初的建议没有奏效。经过更多的试验,我想出了一些可行的方法并相应地编辑了我的答案
    猜你喜欢
    • 1970-01-01
    • 2016-07-11
    • 2012-10-20
    • 1970-01-01
    • 2014-11-03
    • 2011-07-29
    • 1970-01-01
    • 1970-01-01
    • 2013-06-25
    相关资源
    最近更新 更多