简体   繁体   English

在groovy中使用eval

[英]using eval in groovy

How can I use eval in groovy to evaluate the following String: 我如何在groovy中使用eval评估以下字符串:

{key1=keyval, key2=[listitem1, listitem2], key3=keyval2} {key1 = keyval,key2 = [listitem1,listitem2],key3 = keyval2}

All the list items and keyval is a String. 所有列表项和keyval是一个字符串。

doing Eval.me("{key1=keyval, key2=[listitem1, listitem2], key3=keyval2}") is giving me the following error: 做Eval.me(“ {key1 = keyval,key2 = [listitem1,listitem2],key3 = keyval2}”)给我以下错误:

Ambiguous expression could be either a parameterless closure expression or an isolated open code block; 歧义表达式可以是无参数闭包表达式或隔离的开放代码块; solution: Add an explicit closure parameter list, eg {it -> ...}, or force it to be treated as an open block by giving it a label, eg L:{...} at 解决方案:添加一个显式的闭包参数列表,例如{it-> ...},或通过给它一个标签,例如在L处的L:{...},强制将其视为开放块。

I want to get HashMap 我想获取HashMap

Is there no way you can get the data in JSON format? 有没有办法获取JSON格式的数据? Then you could just use one of the parsers mentioned here . 然后,您可以只使用这里提到的解析器之一

You can parse that string by translating some of the characters, and writing your own binding to return variable names when Groovy tries to look them up, like so: 可以通过翻译一些字符解析该字符串,并编写自己的绑定以在Groovy尝试查找它们时返回变量名,如下所示:

class Evaluator extends Binding {
  def parse( s ) {
    GroovyShell shell = new GroovyShell( this );
    shell.evaluate( s )
  }
  Object getVariable( String name ) { name }
}

def inStr = '{key1=keyval, key2=[listitem1, listitem2], key3=keyval2}'
def inObj = new Evaluator().parse( inStr.tr( '{}=', '[]:' ) )

println inObj

But this is a very brittle solution, and getting the data in a friendlier format ( as suggested by @Stefan ) is definitely the best way to go... 但这是一个非常脆弱的解决方案,以更友好的格式( 如@Stefan所建议的那样 )获取数据绝对是最好的方法...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM