Search code examples
grailsgroovygrails-orm

Grails how to JSONify domain object including its nested domain classes?


I am trying to do one to many domain mapping in grails.Here are the two classes :

class TNDetails {

String tn
String tnpk

static hasMany = [iccid: ICCID]

static mapping = {
    table 'ni_tn'
    version false
    tnpk column : 'TN_PK'
    tn column: 'TN'
    id column: 'TN_PK',name: 'tnpk'
    }

}

class ICCID {

String sim
String customer
static belongsTo = [tn: TNDetails]


static mapping = {
    table 'ni_sim'
    version false
    sim column: 'ICCID'
    customer column: 'CUSTOMER'
    tn column: 'TN_FK'
    id column: 'SIM_PK'
  }
}

The corresponding query can be written as : select TN,ICCID from ni_tn,ni_sim where ni_tn.TN_PK = ni_sim.RELATED_TN and tn_pk=1290.Now in my controller when i am fetch the details by passing tn_pk like this :

def index() {
    def pk = params.tnPK
    def details = TNDetails.findAll   {

        (tnpk == pk)

    }

    respond details
}

i get following result : [ { "class": "com.evolving.resource.tn.TNDetails", "id": 1290, "tnpk": "1290", "iccid": [ { "class": "com.evolving.resource.iccid.ICCID", "id": 4209 } ], "tn": "447400002035" } ]

Now the problem here is it is not displaying the attributes sim and customer(from class ICCID).How do i display these two parameters also.What am i doing wrong here?


Solution

  • change your:

    respond details
    

    to:

    JSON.use("deep") {
        respond details as JSON
    }
    

    The Deep Converters fully render the associations (nested domainclass instances) and also handle circular relations (documentation)