Reputation: 15
I've just started working with Grails 2.4.4 and I'm trying to create a REST api which outputs JSON but I have a problem with it when it comes to render the object as JSON. Listed below are the domain class, controller and the objectmarshall.
Domain class :
@Resource(uri='/users')
class User {
List contacts;
String name;
String password;
static hasMany=[contacts:Contact]
static constraints = {
}
static mapping = {
contacts lazy: false
}
}
Controller :
class UserController {
def index() {
//json
render User.getAll() as JSON
}
Boostrap groovy :
class BootStrap {
def init = { servletContext ->
JSON.registerObjectMarshaller(User) {
def output = [:]
output['id'] = it.id
output['name'] = it.name
output['contacts'] = it.contacts
return output;
}
JSON.registerObjectMarshaller(Contact) {
def output = [:]
output['id'] = it.id;
output['name'] =it.name;
output['phoneNumber'] = it.phoneNumber;
output['userId'] = it.user.id;
return output;
}
}
}
After I run my application the first time,it returns XML instead of JSON but if I make a new change that will generate a hot deploy(for e.g if I add a comment) it will generate JSON.
What am I missing?
Upvotes: 0
Views: 2466
Reputation: 1219
I find creating a map of what you want and rendering that is much simpler.
def renderMe = [name: "Joe"]
render renderMe as JSON
Upvotes: 1
Reputation: 394
Try to declare content type with render(contentType:"application/json")
Upvotes: 1