Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 38 ยท Builders, DSLs and Templates

MarkupBuilder, JsonBuilder and Custom Builders in Groovy

Generate HTML, XML and JSON in Groovy with MarkupBuilder, StreamingMarkupBuilder and JsonBuilder, then write your own builder with BuilderSupport.

Writing XML or JSON by gluing strings together is error-prone: forget one closing tag or one escape and the output is broken. Groovy's builders let you describe the structure with nested method calls, and the builder turns it into correct text. They are the best known example of the delegate DSLs from the previous lesson: a method call like book(id: 1) { ... } is interpreted by the builder as "an element named book".

Groovy cannot run on this site, so the Groovy fences are read-only, and any output is shown only where it is exact. The Java stand-ins write a tiny tree builder so you can see the mechanism.

MarkupBuilder

groovy.xml.MarkupBuilder writes XML or HTML to any Writer.

GROOVY
import groovy.xml.MarkupBuilder

def writer = new StringWriter()
def xml = new MarkupBuilder(writer)

xml.library(name: "City") {
  book(id: 1) {
    title("Dune")
    author("Frank Herbert")
  }
  book(id: 2) {
    title("Emma")
    author("Jane Austen")
  }
}
println writer

Prints:

XML
<library name='City'>
  <book id='1'>
    <title>Dune</title>
    <author>Frank Herbert</author>
  </book>
  <book id='2'>
    <title>Emma</title>
    <author>Jane Austen</author>
  </book>
</library>

How the code is read:

  • xml.library(...) is a call to a method that does not exist, so the builder intercepts it (methodMissing) and creates an element library.
  • A map argument becomes attributes, a string argument becomes text, and a closure argument becomes the children.
  • Special characters in text and attributes are escaped for you.

Because it is just Groovy, you can use loops and conditions inside:

GROOVY
def books = [[1, "Dune"], [2, "Emma"]]
xml.shelf {
  books.each { id, t ->
    book(id: id, t)
  }
}

If an element's name clashes with a method (for example title might clash in some contexts) call it with "title"("text") or xml.'title'("text"), and use mkp.yield to write text and mkp.yieldUnescaped to write raw text.

Building HTML

GROOVY
xml.html {
  head { title "Groovy page" }
  body {
    h1 "Hello"
    ul {
      ["a", "b"].each { li it }
    }
  }
}

The same builder produces HTML because HTML is just XML-shaped markup. Use MarkupBuilder for documents, or StreamingMarkupBuilder when you need a lazily written stream with namespaces and mkp helpers, such as mkp.xmlDeclaration().

JsonBuilder

groovy.json.JsonBuilder has the same nested-call style, but builds JSON.

GROOVY
import groovy.json.JsonBuilder

def json = new JsonBuilder()
json {
  name "Ada"
  skills(["math", "code"])
  address {
    city "London"
  }
}
println json.toString()
// {"name":"Ada","skills":["math","code"],"address":{"city":"London"}}
println json.toPrettyString()

You can also pass a map or list directly: new JsonBuilder([a: 1, b: [2, 3]]). For writing straight to a stream without keeping the structure in memory, use StreamingJsonBuilder. For one-off conversion, JsonOutput.toJson(obj) is a one-liner, and JsonOutput.prettyPrint(str) formats a string.

Writing your own builder

When you need a builder for a domain (a menu, a UI, a query) extend groovy.util.BuilderSupport, or the friendlier FactoryBuilderSupport. BuilderSupport needs these hooks:

GROOVY
class TreeBuilder extends BuilderSupport {
  int depth = 0
  StringBuilder out = new StringBuilder()

  protected Object createNode(Object name) {
    out << "  " * depth << name << "\n"
    depth++
    return name
  }
  protected Object createNode(Object name, Object value) {
    out << "  " * depth << name << ": " << value << "\n"
    depth++
    return name
  }
  protected Object createNode(Object name, Map attrs) {
    createNode(name, attrs.toString())
  }
  protected Object createNode(Object name, Map attrs, Object value) {
    createNode(name, value)
  }
  protected void setParent(Object parent, Object child) { }
  protected void nodeCompleted(Object parent, Object node) { depth-- }
}

def b = new TreeBuilder()
b.menu {
  file { open(); save() }
  edit { copy() }
}
println b.out

The base class turns every unknown method call into a createNode, and calls nodeCompleted when the closure for that node ends. Your job is to decide what a node is.

Builders you already use

Builder Output
MarkupBuilder, StreamingMarkupBuilder XML / HTML
JsonBuilder, StreamingJsonBuilder JSON
AntBuilder Runs Apache Ant tasks from Groovy
SwingBuilder Swing user interfaces
NodeBuilder A tree of groovy.util.Node objects
Gradle's own DSL Project model

Try it: a tree builder in Java (stand-in)

This Java builder uses nested lambdas. A child block runs inside the parent block, like a Groovy closure under a createNode.

Java Stand-in: nested element builder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Try it: JSON from nested maps (stand-in)

JsonBuilder is a structure-to-text converter. This Java function does the same for maps and lists, escaping quotes.

Java Stand-in: a small JSON writer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In a MarkupBuilder, what does a map argument such as book(id: 1) become?

    Map arguments are attributes, strings are text, and closures are children.
  2. 2. Why does xml.library { ... } work even though MarkupBuilder has no method named library?

    Builders rely on dynamic dispatch hooks, so unknown method names become nodes.
  3. 3. Which class do you extend to write your own node-style builder?

    BuilderSupport (or FactoryBuilderSupport) provides the createNode and nodeCompleted hooks.
  4. 4. Which call formats a JSON string with indentation?

    JsonOutput.prettyPrint formats existing JSON text, and JsonBuilder offers toPrettyString.

Summary

  • Builders turn nested method calls into structured output, with correct escaping.
  • MarkupBuilder writes XML or HTML; maps are attributes, strings are text, closures are children.
  • JsonBuilder and StreamingJsonBuilder write JSON; JsonOutput converts objects directly.
  • Loops and conditions work inside a builder block because it is normal Groovy.
  • BuilderSupport lets you create builders for your own domain.

Next: Parsing XML and JSON