简体   繁体   中英

How do I handle lazy loaded references when returning a model as JSON in Grails

In Grails I have a model class User that has a one-to-one mapping with another model class Address. When returning a user in JSON format from my controller I never see the address class, just the id. In my User class I have:

class User {

    Address address

    ...

    static mapping = {
        ...
        address fetch: 'join'               
        ...
    }

And then in my controller I do

User user = user.get(1)
render user as JSON

Is there a way to change the mapping to make the 'as JSON' pull back the address class?

I am running on Grails 1.3.7.

There are Two types of JSON Converters ie:

grails.converters.deep.JSON
grails.converters.JSON

.
.
What you need is a Deep Converter, Just change the Imported Class To:

    // Dont Use: import grails.converters.JSON
    import grails.converters.deep.JSON

Note: Grails 1.3.7 import grails.converters.deep.JSON is fiine, in Grails 2.0 its deprecated.

The Difference Between these two is, that the "Deep" one will also JSONify the nested Classes, Whereas Standard Converter will not.

Hope that help

Regards

Kushal

Have you tried setting your converter to be deep?

JSON.use("deep"){ User user = user.get(1) render user as JSON }

There is a bit of stuff around the Custom Object Marshallers that you can dig into here, but my first try would be to just try the deep conversion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM