Groovy web console

subscribe to the feed Subscribe
to this
site
JsonBuilder (via #groovywebconsole)
tweet this snippet Tweet
this
script

JsonBuilder

Published 10 months ago by Suru
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
import groovy.json.JsonBuilder
 
// Example class.
@groovy.transform.Immutable
class Villain {
    String animal_name
}
 
// A list of Villain objects that needs to transformed
// to a JSON array.
def list = ['The Joker', 'Penguin', 'Catwoman', 'Harley Quinn'].collect { anything-> new Villain(anything) }
 
// We create a new JsonBuilder and
// use the list of Villain objects
// as argument for the constructor
// to create a root JSON array.
def json1 = new JsonBuilder(list)

println(json1.toString());
 
assert json1.toString() == '[{"animal_name":"The Joker"},{"animal_name":"Penguin"},{"animal_name":"Catwoman"},{"animal_name":"Harley Quinn"}]'
 
 
// Here we use the no-argument constructor
// to create a JsonBuilder.
// Then we use the instance implicit
// method call with the list of Villain
// objects as arguments
def json2 = new JsonBuilder()
json2(list)
 
assert json2.toString() == '[{"animal_name":"The Joker"},{"animal_name":"Penguin"},{"animal_name":"Catwoman"},{"animal_name":"Harley Quinn"}]'

println json2.toString()