Skip to content

Instantly share code, notes, and snippets.

@bdelacretaz
Created June 30, 2016 15:07
Show Gist options
  • Save bdelacretaz/c4015290162db7ffaa4f6cff4c2f5379 to your computer and use it in GitHub Desktop.
Save bdelacretaz/c4015290162db7ffaa4f6cff4c2f5379 to your computer and use it in GitHub Desktop.
Groovy JsonBuilder experiments
// Demonstrate various features of the Groovy StreamingJsonBuilder
// run this with groovy <filename>
// See below for typical output
// A Groovy class
class Resource { String path; String resourceType }
// Groovy list of resources
resources = [
new Resource(path:"/tmp/one", resourceType:"my/example"),
new Resource(path:"/tmp/two", resourceType:"my/example"),
new Resource(path:"/tmp/two/k", resourceType:"other/type"),
]
// Test on a pure Java collection as well
list = new ArrayList<Resource>()
list.add(new Resource(path:"foo", resourceType:"T2"))
list.add(new Resource(path:"foo2", resourceType:"T3"))
list.add(new Resource(path:"bar", resourceType:"T4"))
out = new java.io.OutputStreamWriter(System.out)
// Here's the builder
new groovy.json.StreamingJsonBuilder(out)
.testingTheBuilder {
person {
lastName 'DaVinci'
address(
city: 'Manchester',
country: 'UK',
zip: "M1 2AB",
)
living true
dynamicValue "Current date is ${ new java.util.Date() }"
eyes 'left', 'right'
}
playingWithResourceObjects {
rawChildren resources
convertedChildren resources.collect { r -> [ "upperPath":r.path.toUpperCase() ] }
filteredChildren (
resources.findAll { it.path.contains("two") }
.collect { r -> [ "justPath":r.path ] }
)
}
dataFromJavaTypes {
rawList list.each {}
filteredList (
list.findAll { it.path.contains("foo") }
.collect { r -> [ resourceType:r.resourceType ] }
)
}
}
out.flush()
/* Typical output
{
"testingTheBuilder": {
"person": {
"lastName": "DaVinci",
"address": {
"city": "Manchester",
"country": "UK",
"zip": "M1 2AB"
},
"living": true,
"dynamicValue": "Current date is Thu Jun 30 16:56:57 CEST 2016",
"eyes": [
"left",
"right"
]
},
"playingWithResourceObjects": {
"rawChildren": [
{
"resourceType": "my/example",
"path": "/tmp/one"
},
{
"resourceType": "my/example",
"path": "/tmp/two"
},
{
"resourceType": "other/type",
"path": "/tmp/two/k"
}
],
"convertedChildren": [
{
"upperPath": "/TMP/ONE"
},
{
"upperPath": "/TMP/TWO"
},
{
"upperPath": "/TMP/TWO/K"
}
],
"filteredChildren": [
{
"justPath": "/tmp/two"
},
{
"justPath": "/tmp/two/k"
}
]
},
"dataFromJavaTypes": {
"rawList": [
{
"resourceType": "T2",
"path": "foo"
},
{
"resourceType": "T3",
"path": "foo2"
},
{
"resourceType": "T4",
"path": "bar"
}
],
"filteredList": [
{
"resourceType": "T2"
},
{
"resourceType": "T3"
}
]
}
}
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment