Marshall JSON and XML in your own way
Has there been instances when you wished to exclude certain properties while generating JSON object from a POJO and felt we had no control over it? Recently I was stuck with the same requirement and that’s what we are going to discuss in this blog post.
Lets say, I have a “User” class as given below and which of course has a password field too. We would never like it to be a exposed when rendered as JSON / XML.
[code]
class User {
String firstName
String lastName
String email
String password
}
User user = new User(firstName:”first name”,lastName:”last name”,email:”your email”,password:”your password”)
render user as JSON
//output
{“firstName”:”first name”,“lastName”:”last name”,”email”:”your email”,”password”:”your password”}
[/code]
So now the question is how to exclude this password from User Json? Well, after some research I found we could define the way JSON would get marshalled. We need to do two things for the same :
1. Register the marshaller :
It could be done in BootStrap.groovy as given below :
[code]
//For JSON
JSON.registerObjectMarshaller(new org.codehaus.groovy.grails.web.converters.marshaller.json.InstanceMethodBasedMarshaller())
//For XML
XML.registerObjectMarshaller(new org.codehaus.groovy.grails.web.converters.marshaller.xml.InstanceMethodBasedMarshaller())
[/code]
2. Define your own marshaller in the POJO :
[code]
class User {
String firstName
String lastName
String email
String password
JSON toJSON(json) {
json.build {
firstName(firstName)
email(email)
fullName(firstName+lastName)
}
}
}
[/code]
Voilla! Its that simple. Now, as you are expecting the output would be
[code]
{“firstName”:”first name”,”email”:”your email”,”fullName”:”first name last name”}
[/code]
same goes for the XML response.
Hope this helped.
Thank You,
Jeevesh Pandey