Tuesday, November 17, 2009

Groovy JSON / Using json-lib with Groovy / Using json_simple with Groovy

After a bit of research I've concluded there are two clear options for using JSON with groovy.

1) Using json-lib . Note the annotation is Groovy 1.7 syntax and it rocks.

import net.sf.json.groovy.*
@Grab(group='net.sf.json-lib', module='json-lib', version='2.3', classifier='jdk15')

def books = builder.books {
book(title: "Groovy in Action", author: "Dierk Koenig")

assert books.toString() == '''{"books":{
"book":{"title":"Groovy in Action","author":"Dierk Koenig"}}}'''

2) Using the json_simple library .

import org.json.simple.JSONValue;
def response = [ : ];

response.error = [ message : "Not authorized" ];
def jsonString = JSONValue.toJSONString( response );
def deserializedResponse = JSONValue.parse( jsonString );
I prefer 2) but to be honest I haven't looked into Builders much. There's a simple analogy between Groovy datastructures and JSON. Why complicate it any further?


At May 17, 2010 at 12:25 PM , Blogger Steve said...

cool! -- is there a way to Grab the import org.json.simple.JSONValue lib?


Post a Comment

Subscribe to Post Comments [Atom]

<< Home