在Groovyshell中执行变量代码

时间:2015-01-21 16:32:45

标签: groovy groovyshell

考虑这段代码

 def RespJson = RespSlurper.parseText(content)    
 def RespNode= "RespJson"+"."+ assertionKey

其中assertionKey将在每次迭代时动态更改,并且其值将为seatbid[0].bid[0].impid

如何在Groovyshell中执行以下代码,我正在尝试这个

def v    
def a = new Binding(RespJson: RespJson)
new GroovyShell(a).evaluate(" v=${RespNode}")
log.info(v)

但我得到v的值为null。任何帮助表示赞赏。感谢。

修改

def RespSlurper = new JsonSlurper()
def content = step.testRequest.response.responseContent

content的值为

{  
   "seatbid":[  
      {  
         "bid":[  
            {  
               "id":"1",
               "impid":"1",
               "price":3.5999999046325684,
               "nurl":"http:...",
               "adomain":[  
                  "zagg.com",
                  "zagg.com"
               ],
               "iurl":"http:...",
               "crid":"30364.s320x50m",
               "h":0,
               "w":0
            }
         ],
         "group":0
      }
   ],
   "cur":"USD",
   "nbr":0
}

1 个答案:

答案 0 :(得分:1)

我有下面的代码,因为我认为这是问题的简要版本。

在这种情况下,似乎可以从绑定中检索v变量,即a。绑定的变量在variables对象上可用。

此外,由于GroovyShell评估的脚本与v设置的脚本相同,因此打印GroovyShell对象的输出也将打印" 1"。

import groovy.json.JsonSlurper

def RespSlurper = new JsonSlurper()
def content = '{"seatbid":[{"bid":[{"id":"1","impid":"1","price":3.5999999046325684,"nurl":"http:...","adomain":["zagg.com","zagg.com"],"iurl":"http:...","crid":"30364.s320x50m","h":0,"w":0}],"group":0}],"cur":"USD","nbr":0}'
def RespJson = RespSlurper.parseText(content)
def assertionKey = "seatbid[0].bid[0].impid"
def RespNode= "RespJson"+"."+ assertionKey
def v
def a = new Binding(RespJson: RespJson)
def result = new GroovyShell(a).evaluate("v=${RespNode}")
println(v)
// Important addition!
println(result)         <=== print the value of the GroovyShell, it will show "1"
println(a.variables.v)  <=== retrieve the "v" variable off of the binding, it will show "1"