Skip to content

Instantly share code, notes, and snippets.

@zanthrash
Created February 12, 2012 02:36
Show Gist options
  • Save zanthrash/1805881 to your computer and use it in GitHub Desktop.
Save zanthrash/1805881 to your computer and use it in GitHub Desktop.
Grails JsonBuilder Example
import groovy.json.*
class Person {
String name
List addresses = []
}
class Address {
String address
String state
}
Person p = new Person(name:"Frank")
p.addresses << new Address(address: "123 Street", state:"MN")
p.addresses << new Address(address: "987 Ave", state:"WI")
def builder = new JsonBuilder()
def root = builder.people {
person {
name "${p.name}"
addresses(
p.addresses.collect{
Address a -> [addr: a.address, state:a.state]
}
)
}
}
println builder.toPrettyString()
{
"people": {
"person": {
"name": "Frank",
"addresses": [
{
"addr": "123 Street",
"state": "MN"
},
{
"addr": "987 Ave",
"state": "WI"
}
]
}
}
}
<people>
<person>
<name>Frank</name>
<addresses>
<address>
<addr>123 Street</addr>
<state>MN</state>
</address>
<address>
<addr>987 Ave</addr>
<state>WI</state>
</address>
</addresses>
</person>
</people>people
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment