0

I want to use the model field in an Interceptor for a JSON REST response.

The controller method responds with the domain object:

def show(String id) {
    respond User.get(id)
}

The JSON view uses JsonViewJsonRenderer which extends DefaultViewRenderer, which directly calls

  view.render(model, request, response)

and doesn't to expose a ModelAndView instance. Other renderers e.g. DefaultHtmlRenderer, expose the model via:

 applyModel(context, object)

Is there a way to get the model field to be filled out when responding with a JSON response? Do I need to build my own subclass of DefaultHtmlRenderer that sets the ModelAndView?

As a workaround, I could create a ModelAndView for each response, but this seems to not be in the ease-of-use spirit of Grails:

def show(String id) {
    respond new ModelAndView('user/show', User.get(id))
}
flicken
  • 15,443
  • 4
  • 29
  • 29

1 Answers1

0

Is there a way to get the model field to be filled out when responding with a JSON response?

Yes. There is a model property available in all interceptors. Typically this would be accessed in the after() method of an interceptor.

Do I need to build my own subclass of DefaultHtmlRenderer that sets the ModelAndView?

No.

Jeff Scott Brown
  • 26,804
  • 2
  • 30
  • 47
  • Sounds like this is a bug in `views-json` / `JsonViewJsonRenderer` then, because the model is `null` in the `after()` method. I'll create an example project to demonstrate, along with a workaround. – flicken Sep 28 '20 at 06:51
  • Example repo of issue: https://github.com/flicken/grails-json-interceptor-missing-model – flicken Sep 28 '20 at 10:33
  • Created as issue on grails-views https://github.com/grails/grails-views/issues/235 – flicken Sep 28 '20 at 13:09