24

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 ?

5 Answers 5

37

If you are on Groovy 1.8 or later, there is a build in JsonSlurper you can use this way:

import groovy.json.JsonSlurper

//Attention: you have to use double quotes inside the json string
def jsonObj = new JsonSlurper().parseText( '{ "name":"Peter", "age": 23}' )

assert jsonObj.name == "Peter"
assert jsonObj.age == 23
//this won't work, because it's not defined
assert jsonObj.gender == null
Sign up to request clarification or add additional context in comments.

3 Comments

JSONSlurper actually causes StackOverflow exceptions on some JSON documents due to liberal use of regexps and caveats in Java regexp implementation. See jira.codehaus.org/browse/GROOVY-4903 (marked as fixed but problem is still present)
JsonSlurper also doesn't deserialize dates from JSON, which is really annoying.
@erturne that may have something to do with Date not being part of the JSON standard. If the JSON you're getting has new Date() or other non-standand syntax, you will need to subclass JsonSlurper, otherwise you can just iterate over and fix the returned map.
14

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.

In the code above, mapper is an instance of com.fasterxml.jackson.databind.ObjectMapper from the Jackson library.

2 Comments

what is mapper?
@Gank mapper is an instance of com.fasterxml.jackson.databind.ObjectMapper from the Jackson library
6

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.

3 Comments

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

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()

1 Comment

At this time, you need to use "new JsonSlurper().parseText" instead of using "new JsonSlurper().parse"
3

To the people having trouble with json-lib and GJson.enhanceClasses(). Try GJson.enhanceString() instead.

GJson.enhanceString()
def o = "{\"x\": 20.0}" as JSONObject

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.