Search code examples
jsongrailsgrails3grails3.2.0json-view

How to use Grails JSON view without defining internal templates?


I've a domain class:

class Business {
    String name
    String description
}

I have the following JSON templates :

index.gson: to generate the JSON for the list of objects

_business.gson: to generate JSON for Business object

index.gson

import server.Business
model {
    Iterable businessList
}
json {
    result tmpl.business(businessList ?: [])
}

_business.gson

model {
        Business business
}
json {
    id business.id
    name business.name
} 

HOW can I generate JSON for Business object without using _business.gson template?

I want to go for a approach where I just have the index.gson and manually render the internal object.

import server.Business
model {
    Iterable businessList
}

json {
    **WHAT SHOULD I ADD HERE?**
}

json(businessList.toList()) {
    **I also noticed that I can use this syntax, BUT WHAT SHOULD I ADD HERE?**
}

Solution

  • You can do whatever you want inside the json closure.

    json(businessList.toList()) { Business business ->
        id business.id
        name business.name
        description business.description
    }