Skip to content

Instantly share code, notes, and snippets.

@ktuukkan
Last active December 29, 2021 05:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ktuukkan/8753246 to your computer and use it in GitHub Desktop.
Save ktuukkan/8753246 to your computer and use it in GitHub Desktop.
Custom Grails JSON marshalling
package example
import example.Book
import grails.converters.JSON
class BookController {
// e.g. GET '../rest/books/$bookId'
def show = {
// nothing special here, just render domain objects as usual
render (Book.findById(params.int('bookId')) as JSON)
}
}
package example
import example.Book
import example.Author
import grails.converters.JSON
/**
* Probably the cleanest way to define custom JSON marshalling in Grails.
*
* Imagine Book and Author are domain classes with some typical fields.
*
* File location: src/groovy/example
*/
class JsonMarshallers {
// call this in BootStrap init()
static init() {
JSON.registerObjectMarshaller(Author, authorMarshaller)
JSON.registerObjectMarshaller(Book, bookMarshaller)
}
// marshaller is simply a closure taking a domain class and returning a map
static authorMarshaller = { Author author ->
return [
firstName: author.firstName,
lastName: author.lastName,
numberOfBooks: author.books?.size()
]
}
static bookMarshaller = { Book book ->
return [
isbn: book.isbn,
title: book.title,
author: "${book.author?.lastname}, ${book.author?.firstname}",
year: book.releaseDate?.format("yyyy"),
publisher: book.publisher?.name,
pages: book.pageCount
]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment