Marshall JSON and XML in your own way

04 / Jul / 2014 by jeevesh 0 comments

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.


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”}

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 :

//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()) 

2. Define your own marshaller in the POJO :

class User {

    String firstName
    String lastName
    String email
    String password

    JSON toJSON(json) {
         json.build {
              firstName(firstName)
              email(email)
              fullName(firstName+lastName)
         }
    }
}

Voilla! Its that simple. Now, as you are expecting the output would be


{“firstName”:”first name”,”email”:”your email”,”fullName”:”first name last name”}

same goes for the XML response.

Hope this helped.

Thank You,
Jeevesh Pandey

Tag -

FOUND THIS USEFUL? SHARE IT

Leave a comment -