json converter « Intelligrape Groovy & Grails Blogs

Posts Tagged ‘ json converter ’

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

Posted by Salil on May 13th, 2010

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<Company> companyList = Company.list()
List<Contact> 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

  • Share/Bookmark