Last active
December 29, 2021 05:05
-
-
Save ktuukkan/8753246 to your computer and use it in GitHub Desktop.
Custom Grails JSON marshalling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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