bythe4mile
bythe4mile

Reputation: 642

Rendering json views from controller in Grails

I found that Grails 3.2+ supports json views which provides an elegant way for the response to have json.

So is there a way such that instead of having the ".json" in the request URL, we render a custom JSON template from the controller. I tried using the render method, but keep getting an error that the template could not be found. Additionally reading through the documentation I can't seem to find a way to do this. Is this something that is supported yet?

Upvotes: 2

Views: 1295

Answers (2)

user2782001
user2782001

Reputation: 3488

You can use render(json:"path") to render arbitrary gson views from the controller.

SomethingController{

def giveMeJson(){
      render(json:"my_template",model:[some_data:some_instance])
}

}

Upvotes: 0

James Kleeh
James Kleeh

Reputation: 12228

Having .json in the url is just another way to specify the accept content type. You can specify the header instead.

For instructions on how to use json views, read the documentation: http://views.grails.org/latest/

class Controller {
    def index() {
        [foo: new Foo()]
    }
}

/grails-app/views/controller/index.gson

@Field Foo foo

json g.render(foo)

Upvotes: 1

Related Questions