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 ?

Jaime Caffarel
  • 2,401
  • 4
  • 30
  • 42
Wavyx
  • 1,715
  • 2
  • 14
  • 23
  • 1
    native "groovy properties" are not known to pure java libraries (i.e. libraries working on java reflection / java beans) – Jacek Cz Nov 24 '16 at 16:40

3 Answers3

161

Do you mean like:

import groovy.json.*

class Me {
    String name
}

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

println new JsonBuilder( o ).toPrettyString()
tim_yates
  • 167,322
  • 27
  • 342
  • 338
  • 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 Jan 08 '14 at 15:28
  • @Wavyx Yeah, then it doesn't make it into `metaClass.properties`, so isn't picked up by the builder :-/ – tim_yates Jan 08 '14 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 Jan 08 '14 at 15:32
  • Or maybe: `new JsonBuilder( this.getClass().declaredFields.findAll { !it.synthetic }.collectEntries { [ (it.name):this[ it.name ] ] } ).toString()` – tim_yates Jan 08 '14 at 15:40
28

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))
chim
  • 8,407
  • 3
  • 52
  • 60
11

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()
dhamibirendra
  • 3,016
  • 23
  • 26