Grails – small and simple method to convert objects to JSON
I was playing around with Grails and JSON and came up with a small method to convert a given collection of objects into JSON (typically, domain class objects, but it would work with anything). It’s nothing new or fancy, but maybe usefull for anybody who is starting to explore Grails JSON capabilities. For the sake of the example, I’ll put the method in a JSONUtils class:
import grails.converters.JSON class JSONUtils { protected static buildJSON(objectsToBuild, properties) { objectsToBuild.inject([], { objects, object -> objects << (properties.inject([:], { objectMap, property -> objectMap << [(property): object[property]] })) }) as JSON } }
You could use it in a controller as following:
import static JSONUtils.buildJSON class PersonController { def personService static personJSONProperties = [ 'name', 'gender', 'age'] def peopleByAge(Integer age) { buildJSON(personService.findByAge(age), personJSONProperties) } }
I'm thinking that this could be a small but usefull AST transformation...
Parecidos razonables
-
Grails – generic methods for equals and hashCode calculation
December 27, 2012
3 -
New Grails plugin – Timestamped
June 3, 2013
0 -
Grails – Quickly examine a domain class associations
July 30, 2013
0 -
Grails – my domain class instance says its class is abstract!
November 18, 2013
0 -
Groovy – using parameters with default values to separate method configuration from method body
November 23, 2012
0
Conversaciones