How to use a JSON View in a Grails Service

You can render a model into JSON with a JSON View within a Grails service:

Given the following view:


import example.Contact

model {
    Contact contact
json {

You can create a service such as:

package example

import grails.plugin.json.view.JsonViewTemplateEngine
import groovy.text.Template
import org.springframework.beans.factory.annotation.Autowired

class JsonViewRenderingService {
    JsonViewTemplateEngine jsonViewTemplateEngine

    Writable renderWritable(String templatePath, Map<String, Object> model) {

    String render(String templatePath, Map<String, Object> model) {
        renderWritable(templatePath, model)
            .writeTo(new StringWriter())

Which you can call from other Grails Artifacts:

[contact: new Contact(name: 'Sergio')])

Kudos to @virtualdogbert for this trick.

Tags: #grails #json-view
Sep 2021, 22.


My next events:
🗓 Oct 05 17:00 Jumpstart your Java applications with AWS Lambda and Micronaut