Tuesday, December 1, 2009

Groovy Serialization

Groovy's lists and maps provide the simple building blocks of more complex structures. Occasionally you want to serialize these complex structures to files/streams/whatever. Previously I wrote about using JSON with Groovy. While this is still my weapon of choice for this problem, another alternative would be to use the ConfigObject and the ConfigSlurper classes from the Groovy API.

Here's how you would serialize the data using this method:

//create the datastructure
def configObj = new ConfigObject()
configObj.testing = [1, 2, 3]
configObj.nested = [ objects : 'wtf' ]

//serialize it
new File( 'newout.groovy' ).withWriter{ writer ->
configObj.writeTo( writer )

Then when you want to parse it:

def config = new ConfigSlurper().parse(new File('newout.groovy').toURL())
println config

One disadvantage of this method is that the highest level structure must be a map, since that's what ConfigObject inherits from. The data also contains a lot of white-space formatting. Which could be a good or bad depending on the problem you're solving.

Labels: ,


Post a Comment

Subscribe to Post Comments [Atom]

<< Home