JSON Views (Getting started with Grails 3.1 and IntelliJ)

Rumour has it that many people out there have started development with Grails 3.1. Woah!! Wait a sec, You didn’t try JSON views, right ? Believe me, you guys seriously need to know this awesome feature in Grails 3.1. 

Said that, let’s get started!

JSON Views is the new view technology introduced in Grails 3.1. With Grails 3.1, the community is supporting JSON views as the default way to present JSON output to the client and for that reason, the section on writing custom marshallers has been removed from the user guide.

You will find a detailed guide on how to write JSON view (*.gson) files here and in Grails official documentation, but what I found difficult was “How to actually use it”, so I am going to explain the same in this blog. Also, I will deal with setting up IntelliJ for *.gson files. Grails views also have dedicated docs here.

Let’s assume we have a domain called User and it’s respective controller UserController.
Make sure you are using the rest-api profile or have added the required plugins in your build.gradle file.

So, you have your project hierarchy similar to grails-app/domain/com/example/User and grails-app/controllers/com/example/UserController.

class User { String firstName String lastName int age } class UserController { def index() { respond User.list(params) } def show() { respond User.get(params.id) } def update() { // ….your code here if (user.hasErrors()) { respond user.errors } } } Now we want to create JSON views for this controller and its endpoints. Grails by convention will render your JSON view (*.gson file), so you need to place your *.gson files in the appropriate package. Like for User domain, you need to place it under grails-app/views/user/*.

Grails by default look for <_domain.gson> file for the show method. So let’s create our _user.gson file.

model {
    User user

json {
    firstName user.firstName
    lastName user.lastName
    age user.age

When you respond with User.get(params.id) in your show method, Grails will by default respond using the _user.gson view.
Similar to this, when you respond with user.errors from any endpoint, Grails will look for _errors.gson in the default package for any domain or if you want to have a common _errors.gson file, then instead of placing it again and again for every domain just place it under grails-app/views/errors/_errors.gson and Grails will use this when you respond with validation errors.

For this to function correctly, you need to take care of the variable name you use in your *.gson model closure.

Like I used User user in _user.gson, similarly the default _errors.gson provided by Grails rest-api profile use Errors errors, like

model {
    Errors errors

This is the default conventions that Grails will use. For index action, it defaults to <domain>List, like userList.

Now for your index action, the index.gson is required, let’s create that

model {
    Iterable<User> userList

json tmpl.user(userList ?: [])  // This uses the _user.gson template.

You can generate these 3 gson files automatically using the grails generate-views command.
If you want to use your pattern for naming these model variables, make sure you send the same from your endpoint, like

model {
    List users

json tmpl.user(users ?: [])

then your action needs to send the same and it will not follow the default convention, so

def index() {
    return [users: User.list()] // this will work but return User.list() will not work.

You can create *.gson file for each action in your controller, just name the gson file using the action name, like for

def test() {
    // Your code here..

you need test.gson file, and then you can customize the JSON response which is in detail mentioned in the docs.

Configuring IntelliJ Idea for Using GSON Files

You need to add a Groovy DSL file called gson.gdsl. For that follow these steps:

1. Inside IntelliJ’s project hierarchy pane, right click on your grails-app directory and go to New -> Other… -> Groovy Script.

2. Now select GroovyDSL script from the dropdown and name your file as gson.gdsl.

3. Click OK and a blank gson.gdsl will be created and opened in the editor. Now paste the following content into it.
You can find the file here.

def gdslScriptContext = context(scope: scriptScope(), filetypes: ["gson"])

contributor([gdslScriptContext]) {
    // the delegate type

    // constants
    property name:"GET", type:"org.springframework.http.HttpMethod.GET"
    property name:"POST", type:"org.springframework.http.HttpMethod.POST"
    property name:"PUT", type:"org.springframework.http.HttpMethod.PUT"
    property name:"OPTIONS", type:"org.springframework.http.HttpMethod.OPTIONS"
    property name:"PATCH", type:"org.springframework.http.HttpMethod.PATCH"
    property name:"DELETE", type:"org.springframework.http.HttpMethod.DELETE"
    property name:"HEAD", type:"org.springframework.http.HttpMethod.HEAD"
    property name:"TRACE", type:"org.springframework.http.HttpMethod.TRACE"

4. Now when you open any GSON file, IntelliJ will provide you autocomplete for model closure, class imports, etc.

Now we are ready for a head start with JSON views.

Hope you found it useful. Thanks for reading.

About CauseCode: We are a technology company specializing in Healthtech related Web and Mobile application development. We collaborate with passionate companies looking to change health and wellness tech for good. If you are a startup, enterprise or generally interested in digital health, we would love to hear from you! Let's connect at bootstrap@causecode.com

Leave a Reply

Your email address will not be published. Required fields are marked *


Do you want to get articles like these in your inbox?

Email *

Interested groups *
Technical articles