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

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

I use this code 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 } 
+4
source share
3 answers

I just struggled with this exact issue this week. I wanted to send the domain class as JSON, but at the same time add the errorMessage property, which could potentially contain additional information.

It turns out that when used as JSON in grails, it sends back the converter object, but it can be turned into a jconObject instance using JSON.parse () which we can easily add to the new values.

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

I think there are several different approaches, but this turned out to be the easiest for me, since I already have custom converters for most of my domain classes, and I did not want to add any other transient properties to my domain object.

+7
source

Failed to return the map containing the success field and the object enclosed 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 verified is the mind ...

+4
source

You can register your own JSON marshaller (e.g. BootStrap.groovy ), for example:

 JSON.registerObjectMarshaller(MyEntity) { MyEntity it -> return [ someField : it.someField, // you should specify fields for output, or put all '.properties' success : true // as I understand you always have 'true' for real entity ] } 

where MyEntity is your class you want to use

+4
source

Source: https://habr.com/ru/post/1413901/


All Articles