Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializing groovy map to string with quotes

I'm trying to persist a groovy map to a file. My current attempt is to write the string representation out and then read it back in and call evaluate on it to recreate the map when I'm ready to use it again.

The problem I'm having is that the toString() method of the map removes vital quotes from the values of the elements. When my code calls evaluate, it complains about an unknown identifier.

This code demonstrates the problem:

m = [a: 123, b: 'test'] print "orig: $m\n"  s = m.toString() print " str: $s\n"  m2 = evaluate(s) print " new: ${m2}\n" 

The first two print statements almost work -- but the quotes around the value for the key b are gone. Instead of showing [a: 123, b: 'test'], it shows [a: 123, b: test].

At this point the damage is done. The evaluate call chokes when it tries to evaluate test as an identifier and not a string.

So, my specific questions:

  1. Is there a better way to serialize/de-serialize maps in Groovy?
  2. Is there a way to produce a string representation of a map with proper quotes?
like image 625
Doug Harris Avatar asked Jan 10 '13 21:01

Doug Harris


People also ask

How do you add double quotes to a string in Groovy?

We can use the slashes if we have a string with both double and single quotes and we don't want to escape them. def singleQuote = 'Single quote string to "demo" double quotes without backslash escape. ' def doubleQuote = "Double quote string let's us use single quote without backslash escape."

Can we convert map to string in Java?

Use Object#toString() . String string = map. toString();

How do I create a map object in Groovy?

2. Creating Groovy Maps. We can use the map literal syntax [k:v] for creating maps. Basically, it allows us to instantiate a map and define entries in one line.

How do I create a key value pair in Groovy?

Maps are generally used for storing key-value pairs in programming languages. You have two options to declare a map in groovy. First option is, define an empty map and put key-value pairs after. Second option is declaring map with default values.


2 Answers

Groovy provides the inspect() method returns an object as a parseable string:

// serialize def m = [a: 123, b: 'test'] def str = m.inspect()  // deserialize m = Eval.me(str) 

Another way to serialize a groovy map as a readable string is with JSON:

// serialize import groovy.json.JsonBuilder def m = [a: 123, b: 'test'] def builder = new JsonBuilder() builder(m) println builder.toString()  // deserialize import groovy.json.JsonSlurper def slurper = new JsonSlurper() m = slurper.parseText('{"a": 123, "b": "test"}') 
like image 167
ataylor Avatar answered Sep 25 '22 12:09

ataylor


You can use myMap.toMapString()

like image 23
DMoney Avatar answered Sep 22 '22 12:09

DMoney