88

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) Commented Nov 24, 2016 at 16:40

3 Answers 3

167

Do you mean like:

import groovy.json.*

class Me {
    String name
}

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

println new JsonBuilder( o ).toPrettyString()
Sign up to request clarification or add additional context in comments.

4 Comments

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 Yeah, then it doesn't make it into metaClass.properties, so isn't picked up by the builder :-/
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 }
Or maybe: new JsonBuilder( this.getClass().declaredFields.findAll { !it.synthetic }.collectEntries { [ (it.name):this[ it.name ] ] } ).toString()
31

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

Comments

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.