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
More From Oodles
Ready to innovate? Let's get in touch
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Shakil Pathan
Shakil is an experienced Groovy and Grails developer . He has also worked extensively on developing STB applications using NetGem .