get domain class with child object

I have two domain classes one is parent and other one is child and i have a hasMany relationship between them. Parent class has many childs and child class belongs to parent class. And here is coding example.

class Parent{
   String name
    static hasMany = [childs:Child] 
    static constraints = {
class Child{
   String name
   static belongsTo = [parent:Parent]
   static constraints={}

Problem is as soon as I get the parent object the child objects associated with parent class were also fetched. But when I convert the object to JSON I don’t see the child object completely I can only able to see the ID’s of child objects. I want to see all columns of child object instead of only Id.

Converted JSON response:


But I want the response which contains name of child object too, as follows

==========================ANSWER ===========================================
1. Default - all fields, shallow associations a. render blah as JSON 2. Global deep converter - change all JSON converters to use deep association traversal a. grails.converters.json.default.deep = true 3. Named config marshaller using provided or custom converters a. JSON.createNamedConfig('deep'){ it.registerObjectMarshaller( new DeepDomainClassMarshaller(...) ) } b. JSON.use('deep'){ render blah as JSON } 4. Custom Class specific closure marshaller a. JSON.registerObjectMarshaller(MyClass){ return map of properties} b. render myClassInstance as JSON 5. Custom controller based closure to generate a map of properties a. convert(object){ return map of properties } b. render convert(blah) as JSON

Option 1, which is default. will not return details of the child obj.

The simplest you can do is use Option 2 to set global deep converter, but be aware this effects ALL domain classes in your app. Which means that if you have a large tree of associations culminating in a top level object and you try to convert a list of those top level objects the deep converter will execute all of the queries to fetch all of the associated objects and their associated objects in turn. –You could load an entire database in one shot 🙂 Be careful.

This entry was posted in Grails, Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s