0

Is there any out of box method in java (groovy) that converts the string like

String s = "[a:12,b:[a:b,c:d]]";

to a Map object with key value pairs.

Update: It is somehow similar to the question asked as Groovy: isn't there a stringToMap out of the box?(Groovy: isn't there a stringToMap out of the box?). The difference is here the keys are of string type which makes easier to parse, since i have retrieved the mentioned map by doing .toString() i am unable to parse by the answered methods because my string actually contains date strings which i need it back to date objects. So it was difficult to parse the whole string.

Community
  • 1
  • 1
Prabin Upreti
  • 498
  • 5
  • 16
  • 1
    I don't believe there is a direct way, but someone has asked more or less the same question before here - http://stackoverflow.com/questions/2212606/groovy-isnt-there-a-stringtomap-out-of-the-box – Tony Junkes Sep 23 '16 at 04:46
  • who hands you down sucha "map"? i bet it's a toString somewhere, and you are way better off preventing that _or_ use some form of serialization, that is actually sane – cfrick Sep 23 '16 at 21:49
  • Yes i did toString() to a map, since i need it to pass it to a controller as a whole and convert it as a map object. – Prabin Upreti Sep 24 '16 at 08:07

2 Answers2

1

You can convert this string to JSON-like format, and simple parse it:

String s = "[a:12,b:[a:b,c:d]]";
def result = new JsonSlurper().setType(JsonParserType.LAX).parseText(s.replaceAll('\\[', '{').replaceAll('\\]', '}'))
Evgeny Smirnov
  • 2,886
  • 1
  • 12
  • 22
1

I have a way that may work depending on your actual data. The problem with your sample data is that you supply unquoted strings b and d as part of the structure:

String s = "[a:12,b:[a:b,c:d]]";

If what you had was actually

String s = "[a:12,b:[a:'b',c:'d']]";

or

String s = "[a:12,b:[a:1,c:2]]";

Then you could just do this:

def map=Eval.me(s)

but as is, eval tries to resolve b and d as variables which aren't defined in the scope.

Bill K
  • 62,186
  • 18
  • 105
  • 157