Annyce Davis

Davis Technology Consulting

  • Home
  • About Me
  • Blog
  • Courses
  • Newsletter

Using Grails’ JSON and HTML Builders

October 20, 2009 by Annyce Davis

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':'http://www.google.com'], ...}

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

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
}
}
}
w.toString()

Resulting HTML that is produced:
<div class=”className”>
<p><b>Title: </b>google</p>
</div>

Share this:

  • Click to share on LinkedIn (Opens in new window) LinkedIn
  • Click to share on Mastodon (Opens in new window) Mastodon
  • Click to share on Bluesky (Opens in new window) Bluesky
  • Click to share on WhatsApp (Opens in new window) WhatsApp
  • Click to share on Reddit (Opens in new window) Reddit

Related

Filed Under: Grails Tagged With: Groovy, JSON

Follow Me

  • Bluesky

Categories

  • Android (61)
  • Career (5)
  • Communication (4)
  • Flutter (1)
  • Git (4)
  • Gradle (4)
  • Grails (23)
  • iOS (1)
  • Java (8)
  • JavaScript (6)
  • Kotlin (17)
  • Life (5)
  • Public Speaking (26)
  • Revenue (2)
  • RxJava (1)
  • Software Development (14)
  • Twitter (3)
  • Uncategorized (11)
  • Video Course (5)

Follow Me

  • Bluesky

Copyright © 2025 · All Rights Reserved · Log in