Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy - Convert object to JSON string

Tags:

json

groovy

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 ?

like image 858
Wavyx Avatar asked Jan 08 '14 15:01

Wavyx


People also ask

What is Groovy JSON JsonSlurper?

JsonSlurper is a class that parses JSON text or reader content into Groovy data structures (objects) such as maps, lists and primitive types like Integer , Double , Boolean and String . The class comes with a bunch of overloaded parse methods plus some special methods such as parseText , parseFile and others.

How does Groovy handle JSON response?

Get an Array Element Your JSON response may also contain arrays. Like any array in Java or Groovy, you can access an array element using arrayName[index] . In this example, we access the item with the index of 0, the first item in the array (the index is zero-based).


2 Answers

Do you mean like:

import groovy.json.*  class Me {     String name }  def o = new Me( name: 'tim' )  println new JsonBuilder( o ).toPrettyString() 
like image 150
tim_yates Avatar answered Sep 27 '22 20:09

tim_yates


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)) 
like image 41
chim Avatar answered Sep 27 '22 22:09

chim