Wednesday, December 2, 2009

Groovy Serialization - Part 2 - Objects

In my previous post I discussed the serialization of simple Groovy data structures. Arbitrary objects can also be serialized using ConfigObject and ConfigSluper and a little trickery. The fact Groovy config files may also contain code makes this all possible.

In order to instantiate objects inside a Groovy config file, you need import the referenced objects. You also need to override the toString to create the proper instantiation string.

package MyPackage
class MyObject {
def data;
String toString() {
def serializedString = "new MyObject( data : '${data}' )"
return serializedString

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

//serialize it
new File( 'newout.groovy' ).withWriter{ writer ->
writer.write( "import ${myObject.getClass().getName()}\n" )
configObj.writeTo( writer )

Parsing it is simple:

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

Finally one could use .metaClass to override the toString of any Java object and make it work with this serialization technique. Be careful not to shoot yourself in the foot by doing this, as other code might expect the regular toString().

Labels: ,


At December 2, 2009 at 7:35 PM , Blogger noah said...

Wouldn't overriding inspect work as well and not mess up toString?

At December 2, 2009 at 8:16 PM , Blogger Geoff Flarity said...

Perhaps? What would the example look like then?


Post a Comment

Subscribe to Post Comments [Atom]

<< Home