tags:

views:

388

answers:

3

I found many things about converting Groovy to JSON, but oddly enough, not the other way.

What is the (best) JSON to Groovy parser around there ?

+1  A: 

JSON-lib claims to be able to transform POGO to JSON and back. If POGO means what I think it does (Plain Old Groovy Object), you're set :).

They give this example:

def strAsJsonObject = "{integer:1, bool: true}" as JSONObject

Update:

I've tried the lib myself, this is the complete code:

import net.sf.*;
import net.sf.json.*;
import net.sf.json.groovy.*;

println "hi"
GJson.enhanceClasses()
def strAsJsonObject = "{integer:1, bool: true}" as JSONObject
println strAsJsonObject

It'll chase you through a marathon of downloading dependencies (ezmorph, commons lang, commons logger) and once you've resolved them all, this is what you get:

Exception in thread "main" org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object '{integer:1, bool: true}' with class 'java.lang.String' to class 'net.sf.json.JSONObject'

According to The mailing list, you get this for not calling GJsonlib.enhanceClasses(), but I did call that, as you can see above.

I've concluded that it's a worthwhile endeavor to hate Groovy's JSON-lib.

nes1983
That produces a cast error. I understood that what the `obj as JSONObject` syntax actually converts a Groovy object to JSON.
Gzorg
I then saw it on the doc, so this should work as intended, but it doesn't work for me.
Gzorg
Have you run GJson.enhanceClasses()?
nes1983
+1  A: 

Because compiled Groovy classes are compatible with Java classes, you should be able to use any Java library for converting JSON to POJOs (or POGOs). Jackson is a fairly popular choice which you can use to convert JSON like this:

String json = '{
  "name" : { "first" : "Joe", "last" : "Sixpack" },
  "gender" : "MALE",
  "verified" : false,
  "userImage" : "Rm9vYmFyIQ=="
}'

to a Map using:

Map<String,Object> userData = mapper.readValue(json, Map.class)

Or if you want to convert the JSON to a Groovy User class:

User userData = mapper.readValue(json, User.class)

This will map properties in the Groovy class to keys in the JSON.

Don
+1  A: 

I use JSON-lib in HTTPBuilder, but I use the JSONSlurper class to parse a string to a JSON instance:

JSON jsonMapObject = new JsonSlurper().parse( "{integer:1, bool: true}" );

To go from Object to JSON, I do this:

//from a map:
new JSONObject().putAll( [one:'1', two:'two']).toString()
//from an object:
JSONObject.fromObject( somePOGO ).toString()
Thom Nichols