Rafael
Rafael

Reputation: 2676

Grails JSON marshallers in domain class

I know in grails i can define diferent JSON marshallers and asign names to them for different uses, which is very nice. However i end with a lot of code in the Bootstrap section and i end with two places where i need to tweak when domain classes changes.

Ithink thi is not good enough and i wonder if it might be possible to define JSON marshallers in the domain class itself.

Do you think would it be a good practice? ... can you provide suggestions on the best approach to achieve this?

Thanks,

Upvotes: 0

Views: 521

Answers (2)

Koloritnij
Koloritnij

Reputation: 1217

In Bootstrap.groovy write this code:

JSON.registerObjectMarshaller(YourClass) { YourClass yourClass->
        Map result = [:]
        result['yourClass.property'] = yourClass.property
        def domain = new DefaultGrailsDomainClass(YourClass)
        domain.persistentProperties.each { GrailsDomainClassProperty property, String propertyName = property.name ->
               result[propertyName] = yourClass[(propertyName)]     
        }           
        return result
    }

Code below add one property, you can name it how u want

 result['yourClass.property'] = yourClass.property

This code add all properties by it's name to map:

domain.persistentProperties.each { GrailsDomainClassProperty property, String propertyName = property.name ->
               result[propertyName] = yourClass[(propertyName)]     
        }     

Upvotes: 1

Gregor Petrin
Gregor Petrin

Reputation: 2931

I wrote a plugin for this purpose specifically. It allows you to use annotations in domain classes, like this:

import grails.plugins.jsonapis.JsonApi
class User {

    static hasMany = [
        pets: Pet
    ]

    @JsonApi
    String screenName

    @JsonApi('userSettings')
    String email

    @JsonApi(['userSettings', 'detailedInformation', 'social'])
    String twitterUsername

    @JsonApi(['detailedInformation', 'userSettings'])
    Set pets

    String neverGetsSerialized

    @JsonApi('detailedInformation')
    Integer getNumberOfTicklyAnimals() {
        pets.count { it.likesTickling }
    }
}

In your controller, you would then call JSON.use('detailedInformation') to activate a specific marshaller.

Upvotes: 2

Related Questions