Search code examples
grailsgroovyjsonbuilder

Unable to reference local variable with JsonBuilder


I have the following code

    AddTicketCommand addTicketCommand = new AddTicketCommand(request.JSON)
    JsonBuilder jsonBuilder = new JsonBuilder()
    jsonBuilder {
        ticket {
            subject addTicketCommand.subject
            requester {
                name currentUser?.name
                email currentUser?.emailAddress
            }
            comment {
                body addTicketCommand.comment
            }
            custom_fields {
                [
                        {
                            id 21857727
                            value addTicketCommand.zenRequestType
                        },
                        {
                            id 21854146
                            value addTicketCommand.zenProductId
                        }
                ]
            }
        }
    }

The addTicketCommand object is not null on line 2 but is undefined within the JsonBuilder closure. Is it not possible to access local variables in groovy from within closure?


Solution

  • You should be able to access addTicketCommand inside the closure as below. Mark the use of "parenthesis" instead of "curly" braces.

    AddTicketCommand addTicketCommand = new AddTicketCommand(request.JSON)
    JsonBuilder jsonBuilder = new JsonBuilder()
        jsonBuilder {
            ticket {
                subject addTicketCommand.subject
                requester {
                    name currentUser?.name
                    email currentUser?.emailAddress
                }
                comment {
                    body addTicketCommand.comment
                }
                custom_fields ([ //Note the use of parenthesis
                    {
                        id 21857727
                        value addTicketCommand.zenRequestType
                    },
                    {
                        id 21854146
                        value addTicketCommand.zenProductId
                    }
                ]) ////Note the use of parenthesis
            }
        }