JSON is a user-friendly format for structuring data into text format. This text can be easily sent to and from a server. Grails framework provides us with an efficient way to convert domain objects, lists, arrays and other different types of objects to JSON Objects, JSON Converter.

Class :

JSON Converter is explained with the help of an example :

Domain :

Call in Controller :

Response :

However, there is a problem with JSON Converter. It reads only the root class objects and not the objects in it’s associated classes. If we require those objects too, like this  :

We need to use either of the following methods :

1. Default – all fields, shallow associations

2. Global deep converter – change all JSON converters to use deep association traversal

3. Named config marshaller using provided

4. Custom Converter

5. Custom Class specific closure marshaller

6. Custom controller based closure to generate a map of properties

JSON Converter uses option 1 has default. The simplest method is to set global deep converter by adding the mentioned code in Option 2 into the Config.Groovy, but keep in mind that this effects all the JSON Converters in your application, which means that if you have a large amount of associations in the top level object and you try to convert a list of those top level objects, the deep converter will fetch all of the associated objects with the top level object. Using option 4 is the easiest way to get all the associated objects in a specific method instead of using the deep converter globally!