Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to add an additional field to Grails JSON response?

I want every JSON response to post-request to contain a field success. What's the best way to add this field there?

I use code like this to generate JSON responses:

try {
    def entity = myService.saveEntity(arg1,arg2)
    render entity as JSON //I want to add artificial field 'success = "yes"' here
} catch (ValidationException e) {
    render parseErrors(e.errors) as JSON //field 'success = "no"' here
}
like image 562
Roman Avatar asked Dec 04 '22 03:12

Roman


2 Answers

I just struggled with this exact issue this week. I wanted to send back a domain class as JSON but at the same time add an 'errorMessage' property that would potentially contain additional information.

Turns out that when using as JSON in grails it sends back a converter object, but its possible to turn that converter instance into a jsonObject using JSON.parse() which we can easily add new values to.

def jsonObject = JSON.parse((entity AS JSON).toString())
jsonObject.put("success", "yes")
render jsonObject as JSON

I think there are a couple of different approaches but this ended up being the easiest for me since I already have custom converters for most of my domain classes and I didn't want to add any other transient properties to my domain object.

like image 78
cengebretson Avatar answered Dec 09 '22 14:12

cengebretson


Could you return a map containing the success field, and the object wrapped inside a separate variable:

try {
    def entity = myService.saveEntity(arg1,arg2)
    render [ success:'yes', val:entity ] as JSON
} catch (ValidationException e) {
    render [ success:'no', val:parseErrors(e.errors) ] as JSON
}

Not tested it mind...

like image 37
tim_yates Avatar answered Dec 09 '22 14:12

tim_yates