Parse JSON Request and Build JSON Response in Grails

This is a summary, how to parse JSON type requests and then build a JSON type response in Grails. With JSON type, i mean requests with header of ‘content-type: application/json’

Parse JSON Requests

Please see post ‘Request Automatic Parsing in Grails

Build JSON Response

From String:
Once its done and ready to respond, here is way to build JSON response from string:

  def responseSome = [
                    'status' : "ok"
  render responseSome as JSON

Here is another way to build JSON resonse:

render(contentType: 'application/json'){
           'status' : "ok"

Both of them do the same thing, build JSON response with header ‘content-type: application/json’

From Collection:
To build JSON response from Collection:

if (!{
            render(contentType: "text/json"){
                def errors = array{
                    for (e in review.errors.allErrors){
                        error field: e.field
                        error message: e.defaultMessage

Here all of the errors are collected from Domain class instance validation and new JSON response is built.

For building JSON response from Domain class or other type, please, see post ‘LocalDate as JSON and other types to custom serialize in Grails

Leave a Reply

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