我有以下代码

    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中的局部变量吗?

最佳答案

您应该能够在闭包内部访问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
        }
    }

关于grails - 无法使用JsonBuilder引用局部变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17537983/

10-11 07:52