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, e.g. {it -> ...}, or force it to be treated as an open block by giving it a label, e.g. 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...
精彩评论