Groovy - Convert object to JSON string

JsonGroovy

Json Problem Overview


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 ?

Json Solutions


Solution 1 - Json

Do you mean like:

import groovy.json.*

class Me {
    String name
}

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

println new JsonBuilder( o ).toPrettyString()

Solution 2 - Json

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

Solution 3 - Json

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWavyxView Question on Stackoverflow
Solution 1 - Jsontim_yatesView Answer on Stackoverflow
Solution 2 - JsonchimView Answer on Stackoverflow
Solution 3 - JsondhamibirendraView Answer on Stackoverflow