1
votes

I'm in the process of writing a custom JSON object marshaller in Grails 2.2.4. The class that I'm trying to convert to JSON has both a belongsTo and a hasMany relationship. I can access the belongTo information presumably because the relationship is 1-* but I can't access the hasMany information in the same way. The following is the code I'm using:

JSON.registerObjectMarshaller( Event){
        Event event -> return [
            id : event.id,
            schoolName : event?.school?.name,
            teachers : [
                teacherName: event?.TEACHERS.toString(),
                ],
            ]
    }

the line teacherName: event?.TEACHERS.toString(), is there to prove that I can access the TEACHERS list which works. I think I need to be able to iterate over the list but I'm not sure how to go about doing that in this context.

Thanks

1

1 Answers

3
votes

Couple options here:

1) Set up a marshaller for Teacher. Then in the marshaller for Event, you can simply do:

teachers : event?.teachers

2) If you don't want to set up a marshaller for Teacher, then do this:

JSON.registerObjectMarshaller(Event){ Event event -> 
    [ 
        id : event.id,
        schoolName : event?.school?.name,
        teachers : event.teachers.collect{ Teacher teacher ->
            [id: teacher.id, name: teacher.name]
        }
    ]
}