Use common method for making json object in grails or java object

Posted By Shakil Pathan | 31-Dec-2015

Hi,

In this blog, I'm going to explain you about how to use a common method for making json object which can be render to mobile application and/or to your web application when both display the same data.

Now a days, mobile application and web aplication shows same data from back end server so you can use a common method for making the json in a service for different domain objects, which improves the code readabily.

def makeJSON( item ){
	def returnVal = [ : ]
	if( item instanceof com.User ){
		returnVal.id = item.id
		returnVal.email = item.username
		returnVal.name = item.name
		returnVal.imageURL = item.imageURL
	} else if ( item instanceof com.Post) {
		returnVal.id: item.id,
		returnVal.content: item.content,
		returnVal.photoURL: item.photoURL
		returnVal.authorName: item.author.name,
		returnVal.dateCreated : item.dateCreated
	}
	return returnVal
}

You can use the above code for making the json object, which you can render to mobile and/or web application.

You can use a number of type of objects to make json and render.

Hope it helps!

Thanks
 

Request for Proposal

Recaptcha is required.

Sending message..