Skip to content

Instantly share code, notes, and snippets.

@christierney
Created April 2, 2012 19:54
Show Gist options
  • Save christierney/2286780 to your computer and use it in GitHub Desktop.
Save christierney/2286780 to your computer and use it in GitHub Desktop.
Generate an embedded JSON list with arbitrary transformations using JsonBuilder
import groovy.json.*
// A list of things we want to include in our json output.
// Here it's a list of maps, but this could be a list of beans.
things = [[id:2, name:'asdf'], [id:3, name:'foo'], [id:5, name:'bar']]
// JsonBuilder is pretty cool!
def json = new JsonBuilder()
json {
// It's easy to add single properties like this...
"a" "b"
"c" 123
// ...and to add a list of objects without changing them...
"things" things
// ...but if you want to apply some transformation to each
// object in the list before outputting it, you can return
// a list of closures. Magic!
"transformed_things" things.collect { t ->
return {"${t.name}" "${t.id}"}
}
}
println json.toString()
// {"a":"b","c":123,
// "things":[{"id":2,"name":"asdf"},{"id":3,"name":"foo"},{"id":5,"name":"bar"}],
// "transformed_things":[{"asdf":"2"},{"foo":"3"},{"bar":"5"}]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment