无法使用JsonBuilder引用局部变量

时间:2013-07-09 00:13:47

标签: grails groovy jsonbuilder

我有以下代码

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

第2行的addTicketCommand对象不为null,但在JsonBuilder闭包中未定义。是否无法从闭包内访问groovy中的局部变量?

1 个答案:

答案 0 :(得分:1)

您应该能够访问闭包内的addTicketCommand,如下所示。标记使用“括号”而不是“卷曲”括号。

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