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
Sep 2021, 22.

 

My next events:
🗓 Jul 20 09:00 Workshop Security in the Micronaut Framework
🗓 Sep 20 09:00 JCON Online 2022 - Getting Started with the Micronaut Framework
🗓 Sep 23 09:00 JCON Online 2022 - Micronaut® Framework and Microstream Java-native persistence engine