Search code examples
grailsgroovyjsonbuilder

Groovy JSONBuilder with Nested Array in Grails


Is there a way to nest JSON arrays using the JSONBuilder in Groovy? More explicitly, I have a Grails application that needs to render something like this:

{
    "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"
                                }
                            ]
                        }
                    }
                }
            }
        ]
    }
}

I am having some trouble getting my Grails controller to build this using the render function as well as explicitly using a JSONBuilder in a service.

Everything seems to work except that the "template" object inside the "templates" array is not getting rendered. Here is the code that is doing the rendering:

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

Solution

  • You're missing a level inside the array closure. Try this:

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