简体   繁体   中英

using eval in groovy

How can I use eval in groovy to evaluate the following String:

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

All the list items and keyval is a String.

doing Eval.me("{key1=keyval, key2=[listitem1, listitem2], key3=keyval2}") is giving me the following error:

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

I want to get HashMap

Is there no way you can get the data in JSON format? 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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