Builders

A builder turns nested method calls into a document. The method name is the element or the key, a map argument is its attributes, and a closure is the content, which is why a builder reads like the document it writes.

MarkupBuilder

markup.groovy

import groovy.xml.MarkupBuilder def writer = new StringWriter() def xml = new MarkupBuilder(writer) xml.catalog { book(id: 1) { title('Groovy') price(9.99) } book(id: 2) { title('Gradle') price(24.99) } } println writer.toString()

groovy markup.groovy

<catalog>
  <book id='1'>
    <title>Groovy</title>
    <price>9.99</price>
  </book>
  <book id='2'>
    <title>Gradle</title>
    <price>24.99</price>
  </book>
</catalog>

The builder writes to the writer as it goes, so the document is complete when the outer closure returns. An attribute is a named argument, and a text element is a call with the text, or a closure with a mkp.yield inside when the text mixes with child elements.

JsonBuilder

jsonbuilder.groovy

import groovy.json.JsonBuilder import groovy.json.JsonOutput def builder = new JsonBuilder() builder.person { name 'Ada' skills(['Groovy', 'Java']) address { city 'London' } } println JsonOutput.prettyPrint(builder.toString())

groovy jsonbuilder.groovy

{
    "person": {
        "name": "Ada",
        "skills": [
            "Groovy",
            "Java"
        ],
        "address": {
            "city": "London"
        }
    }
}

A closure is a nested object and a list is a list, so the shape of the block is the shape of the document. prettyPrint indents the compact form the builder produces; a real API writes the compact one.

From document to builder

The same tree is read by XmlSlurper and JsonSlurper, which the JSON lesson and the XML lesson cover. A builder writes, a slurper reads, and both are in the Groovy jar with no dependency to add.

Related

Article author: Arthur Isaev