Create JSON object Using Grails converter (Only selective fields from lists of objects)

13 / May / 2010 by Salil 6 comments

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()
List companyList = 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

FOUND THIS USEFUL? SHARE IT

comments (6)

  1. feee3

    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?

    Reply
  2. Alin

    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).

    Reply
  3. lukasz

    You can do that a little bit simpler:

    jsonMap.companies = companyList.collect{it.properties[‘id’,’name’]}

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *