Return to Snippet

Revision: 14086
at May 19, 2009 04:22 by kungfoo


Updated Code
/* Book domain class */
class Book {
	int pages
	String title
}

/* Author domain class */
class Author {
	String name
	Date birthDate
}

/* registering custom marshallers in Bootstrap.groovy */
import grails.converters.JSON

class BootStrap {

	def init = { servletContext ->
		JSON.registerObjectMarshaller(Author){	author, json ->
			def birthday = author.birthDate
			json.build{
				"class(author)"
				id(author.id)
				name(author.name)
				info{
					birthdate(year: birthday.year, month: birthday.month, day: birthday.day)
				}
			}
		}
		
		JSON.registerObjectMarshaller(Book){	book, json ->
			json.build{
				"class(book)"
				id(book.id)
				info{
					pages(book.pages)
				}
			}
		}
	}
}

/* code for output in controller */
def list = {
	params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)
	def authors = Author.list( params )
	withFormat{
		json{
			render authors as JSON
		}
		html{
			[ authorInstanceList: authors, authorInstanceTotal: Author.count() ]
		}
	}
}

Revision: 14085
at May 19, 2009 04:20 by kungfoo


Initial Code
/* Book domain class */
class Book {
	int pages
	String title
}

/* Author domain class */
class Author {
	String name
	Date birthDate
}

/* registering custom marshallers in Bootstrap.groovy */
import grails.converters.JSON

class BootStrap {

	def init = { servletContext ->
		JSON.registerObjectMarshaller(Author){	author, json ->
			def birthday = author.birthDate
			json.build{
				"class(author)"
				id(author.id)
				name(author.name)
				info{
					birthdate(year: birthday.year, month: birthday.month, day: birthday.day)
				}
			}
		}
		
		JSON.registerObjectMarshaller(Book){	book, json ->
			json.build{
				"class(book)"
				id(book.id)
				info{
					pages(book.pages)
				}
			}
		}
	}
}

/* code for output in controller */
def list = {
        params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)
				def authors = Author.list( params )
				withFormat{
					json{
						render authors as JSON
					}
					html{
						[ authorInstanceList: authors, authorInstanceTotal: Author.count() ]
					}
				}
    }

Initial URL


Initial Description
Expected Behaviour
==================

*	Both classes should be rendered in the specified custom format when `store/book/list.json` is loaded.
*	Order of how the marshallers are added should not matter.
*	It should be possible to register more than one custom object marshallers.


Bug
===

*	Only the first registered marshaller is picked up as expected.
*	The second one is ignored and the default JSON generated by Grails is returned.
*	The order of the calls to `registerObjectMarshaller` matters, such that if the Book marshaller is added first, that one works. However if the Author marshaller is first, that one works.

Initial Title
registerObjectMarshaller in Grails 1.1, suspected Bug

Initial Tags
groovy

Initial Language
Groovy