Groovy - Convert object to JSON string

Wavyx picture Wavyx · Jan 8, 2014 · Viewed 115.5k times · Source

I'm pretty used to Grails converters, where you can convert any object to a JSON representation just like this (http://grails.org/Converters+Reference)

return foo as JSON

But in plain groovy, I cannot find an easy way to do this (http://groovy-lang.org/json.html)

JSONObject.fromObject(this)

return empty json strings...

Am I missing an obvious Groovy converter ? Or should I go for jackson or gson library ?

Answer

tim_yates picture tim_yates · Jan 8, 2014

Do you mean like:

import groovy.json.*

class Me {
    String name
}

def o = new Me( name: 'tim' )

println new JsonBuilder( o ).toPrettyString()