Using Grails' JSON and HTML Builders

In order to generate JSON in groovy that can then be passed to a Grails controller you should use the JSONBuilder class. This class is part of the Grails util package. The code below demonstrates how to generate JSON and HTML.

Resulting JSON that is produced:
ResultSet {['text':'google', 'url':''], ...}

def writer = new StringWriter();
new grails.util.JSonBuilder(writer).json {
ResultSet {
links.each { link ->
Links(text: link.text, url: link.url)

This is the code to do the same with HTML, you would use the Groovy XML MarkupBuilder instead.

StringWriter w = new StringWriter()
def builder = new groovy.xml.MarkupBuilder(w)

builder.div (class: 'className'){
links.each { link ->
p {
b 'Title: '
builder.yield link.text
Resulting HTML that is produced:
<div class="className">
<p><b>Title: </b>google</p>