Skip to content

Instantly share code, notes, and snippets.

@joeRinehart
Created August 16, 2012 18:46
Show Gist options
  • Save joeRinehart/3372577 to your computer and use it in GitHub Desktop.
Save joeRinehart/3372577 to your computer and use it in GitHub Desktop.
Custom JSON marshalling
// Custom marshalling
springContext.getBean( "customObjectMarshallers" ).register()
package util.marshalling
class CustomObjectMarshallers {
List marshallers = []
def register() {
marshallers.each{ it.register() }
}
}
package recipes
import grails.converters.JSON
import recipes.Recipe
class RecipeMarshaller {
void register() {
JSON.registerObjectMarshaller( Recipe) { Recipe recipe ->
return [
id : recipe.id,
content : recipe.content,
userId : recipe.user.id,
username : recipe.user.username
]
}
}
}
import util.CustomObjectMarshallers
import recipe.RecipeMarshaller
// Place your Spring DSL code here
beans = {
customObjectMarshallers( CustomObjectMarshallers ) {
marshallers = [
new RecipeMarshaller()
]
}
}
[
{"id":1,"content":"foo foo bar bar","userId":"1","username":"joe"},
{"id":2,"content":"woogie woogie whooo","userId":"1","username":"joe"}
]
render Recipe.list() as JSON
JSON.registerObjectMarshaller( Recipe ) { Recipe recipe ->
return [
id : recipe.id,
content : recipe.content,
userId : recipe.user.id,
username : recipe.user.username
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment