85

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 ?

1
  • 1
    native "groovy properties" are not known to pure java libraries (i.e. libraries working on java reflection / java beans)
    – Jacek Cz
    Commented Nov 24, 2016 at 16:40

3 Answers 3

164

Do you mean like:

import groovy.json.*

class Me {
    String name
}

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

println new JsonBuilder( o ).toPrettyString()
4
  • 1
    This is indeed working. But the crazy thing, is if you specify "public String name". If you use public accessor, JsonBuilder seems to ignore them...
    – Wavyx
    Commented Jan 8, 2014 at 15:28
  • @Wavyx Yeah, then it doesn't make it into metaClass.properties, so isn't picked up by the builder :-/
    – tim_yates
    Commented Jan 8, 2014 at 15:29
  • Ok.. only other ugly solutions was def toJsonString(Boolean prettyPrint = false) { Map props = [:] def outObject = Publication.declaredFields.findAll { !it.synthetic && it.name != 'props' }.collectEntries { v -> [ (v.name):this[v.name] ] } outObject << props String json = JsonOutput.toJson(outObject) prettyPrint ? JsonOutput.prettyPrint(json) : json }
    – Wavyx
    Commented Jan 8, 2014 at 15:32
  • Or maybe: new JsonBuilder( this.getClass().declaredFields.findAll { !it.synthetic }.collectEntries { [ (it.name):this[ it.name ] ] } ).toString()
    – tim_yates
    Commented Jan 8, 2014 at 15:40
30

I couldn't get the other answers to work within the evaluate console in Intellij so...

groovy.json.JsonOutput.toJson(myObject)

This works quite well, but unfortunately

groovy.json.JsonOutput.prettyString(myObject)

didn't work for me.

To get it pretty printed I had to do this...

groovy.json.JsonOutput.prettyPrint(groovy.json.JsonOutput.toJson(myObject))
12

You can use JsonBuilder for that.

Example Code:

import groovy.json.JsonBuilder

class Person {
    String name
    String address
}

def o = new Person( name: 'John Doe', address: 'Texas' )

println new JsonBuilder( o ).toPrettyString()
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.