Groovy - Convert an object to a JSON string

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

return foo as JSON 

But in normal groovy, I cannot find an easy way to do this ( http://groovy.codehaus.org/gapi/groovy/json/JsonOutput.html )

 JSONObject.fromObject(this) 

returns empty json strings ...

Did I miss the obvious Groovy converter? Or should I go to jackson or the gson library?

+45
json groovy
Jan 08 '14 at 15:17
source share
3 answers

Do you mean:

 import groovy.json.* class Me { String name } def o = new Me( name: 'tim' ) println new JsonBuilder( o ).toPrettyString() 
+88
Jan 08 '14 at 15:25
source share

I could not get other answers to work in the evaluation console in Intellij, so ...

 groovy.json.JsonOutput.toJson(myObject) 

This works fine, but unfortunately

 groovy.json.JsonOutput.prettyString(myObject) 

didn't work for me.

To make it pretty printed, I had to do it ...

 groovy.json.JsonOutput.prettyPrint(groovy.json.JsonOutput.toJson(bookingParams)) 
+7
Mar 13 '17 at 14:15
source share

You can use JsonBuilder for this.

Code example:

 import groovy.json.JsonBuilder class Person { String name String address } def o = new Person( name: 'John Doe', address: 'Texas' ) println new JsonBuilder( o ).toPrettyString() 
+4
Jan 08 '14 at 3:26
source share



All Articles