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:

grails-app/views/apiContact/_contact.gson

import example.Contact

model {
    Contact contact
}
json {
    fullname contact.name
}

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 {
    @Autowired
    JsonViewTemplateEngine jsonViewTemplateEngine

    Writable renderWritable(String templatePath, Map<String, Object> model) {
        jsonViewTemplateEngine.resolveTemplate(templatePath)
            .make(model)
    }

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

Which you can call from other Grails Artifacts:

jsonViewRenderingService.render('/apiContact/_contact',
[contact: new Contact(name: 'Sergio')])

Kudos to @virtualdogbert for this trick.

Tags: #grails #json-view