Grails – small and simple method to convert objects to JSON

January 12, 2013 at 11:03

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...