0

I have a string that I have obtained by printing a Hashmap in Java:

String a = "{data={field1={field3=value3}, field2={field4=value4, field5=value5}}}"

Is there any function in Java that can parse and convert this string into a Hashmap. For this specific string, this function should return a Map<String, Map<String, Map<String, String>>>.

Saeid BK
  • 309
  • 4
  • 7
  • 3
    Why have you done this? If you wish to serialize data then `toString` isn't the way. – Boris the Spider Jul 08 '16 at 16:19
  • I want to test a function and I need to get contents of a variable with type Map from another function and use it to test my own function. When I print this variable, I get a very long string and I want a parser to return this string back to a hashmap, so that I can use it in my test function. – Saeid BK Jul 08 '16 at 16:25
  • 1
    Why convert it to a `String` at all then? – Boris the Spider Jul 08 '16 at 16:26
  • I want to have the content of that variable by printing it. Do you think I should call the other function in my test function and get its values? To be more specific, I have function `a` that gets its input from function `b`. I want to just test function `a` w/o dealing w/ function `b`. What is the proper way to do that? – Saeid BK Jul 08 '16 at 16:31
  • 1
    Stub function `b` to return some know values. Verify that `a` behaves as expected. – Boris the Spider Jul 08 '16 at 16:33
  • Thanks, I will do that. It just takes a very long time for function `b` to produce its values. That was the reason I wanted to not call function `b` every time I want to test function `a`. – Saeid BK Jul 08 '16 at 16:36
  • 1
    That's why you [stub](https://stackoverflow.com/questions/463278/what-is-a-stub) it! – Boris the Spider Jul 08 '16 at 16:37
  • Thank you so much for your help. I will do that. – Saeid BK Jul 08 '16 at 16:38

1 Answers1

0

Google's guava library has similar parser written. Link to answer : Convert string representing key-value pairs to Map

Community
  • 1
  • 1
prateeknischal
  • 752
  • 4
  • 12
  • 2
    The OP needs _nested_ maps, not just a simple `Map`. This approach won't work. I guess you could expand it to attempt recursive resolution of maps nested as values - but that just sounds like a whole can of worms that no-one should open. – Boris the Spider Jul 08 '16 at 16:29
  • Yes, I guess you are right. The docs does show a `Map` output. Only choice while using this library is to write a recursive parser on the `value` part of the entry. – prateeknischal Jul 08 '16 at 16:39