Created
April 2, 2012 19:54
-
-
Save christierney/2286780 to your computer and use it in GitHub Desktop.
Generate an embedded JSON list with arbitrary transformations using JsonBuilder
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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