Create JSON object Using Grails converter (Only selective fields from lists of objects)
This post might help you if you want to get JSON (JavaScript Object Notation) Object on browser. Grails framework provides you very efficient way to achieve this.
For this you need to import grails JSON convertor in your code.
import grails.converters.JSON
Below is the code snapshot which converts java based lists of Objects to JSON object
HashMap jsonMap = new HashMap() ListcompanyList = Company.list() List employeeList = Employee.list() jsonMap.companies = companyList.collect {comp -> return [id: comp.id, name: comp.name, address: comp.address] } jsonMap.employees = employeeList.collect {emp -> return [id: emp.id, name: emp.name, companyId: emp.companyId, role: emp.role] } render jsonMap as JSON
So you got it – MAGIC lies in “render jsonMap as JSON” statement.
Output sent to Browser:
{ "companies": [ {"id":281,"name":" Company Name Incorporated", "address": "street-address, zone-address, city, state, country, zip12"}, {"id":282,"name":" Other company LLC", "address": "street-address1, zone-address2, city, state, country, zip34"}, ], "employees": [ {"id":123,"name":"Employee123 Name","companyId":281, "role":"Designer"}, {"id":127,"name":"Employee127 Name","companyId":281, "role":"Supervisor"}, {"id":129,"name":"Employee129 Name","companyId":282, "role":"Inspector"} ] }
Isn’t it cool :-). How to use JSON Objects on browser is out of scope of this post. I will try to write another post soon – how to query JSON based data to produce client-side results effectively (example – client side search).
Cheers!!
Salil Kalia
Thanks for this write up it helps me to remember how to code in grails.
Thanks for the good writeup. It actually was once a amusement account it. Look complicated to far added agreeable from you! However, how can we be in contact?
There is any way to create a generic function that except from json output data that hasMany associations?
I need this for a grid where I can’t render columns that contain hasMany references (eg. I have a book list – I can render the book format, but can’t render all the authors refereces).
Thanks Salil for sharing this,
It helped me a lot…!!!
Is this more or less efficient than using registerObjectMarshaller ??
You can do that a little bit simpler:
jsonMap.companies = companyList.collect{it.properties[‘id’,’name’]}