grails.converters.JSON except few properties grails.converters.JSON except few properties json json

grails.converters.JSON except few properties


You can do something like this :

def myClass = MyClass.get(1) //include render myClass.part(include:['val1', 'val2']) as JSON //except render job.part(except:['val2','val3']) as JSON

Bootstrap.groovy :

import org.codehaus.groovy.grails.orm.hibernate.support.ClosureEventTriggeringInterceptor as Eventsclass BootStrap { def grailsApplication def excludedProps = [Events.ONLOAD_EVENT,    Events.BEFORE_DELETE_EVENT, Events.AFTER_DELETE_EVENT,    Events.BEFORE_INSERT_EVENT, Events.AFTER_INSERT_EVENT,    Events.BEFORE_UPDATE_EVENT, Events.AFTER_UPDATE_EVENT]  def init = { servletContext ->     grailsApplication.domainClasses.each{ domainClass ->         domainClass.metaClass.part= { m ->             def map= [:]             if(m.'include'){                 m.'include'.each{                     map[it]= delegate."${it}"                 }             }else if(m.'except'){                 m.'except'.addAll excludedProps                 def props= domainClass.persistentProperties.findAll {                     !(it.name in m.'except')                 }                 props.each{                     map[it.name]= delegate."${it.name}"                 }             }             return map         }     }  }  def destroy = {  }}

If you know how to create our own plugin, then just create one plugin for this, so that you can use it across all the grails applications.


If you want to only include specific properties all the time, you would really want to use the ObjectMarshaller interface. See this article for more details.


Or, you could just create a map of the properties you wanted, then encode them as JSON

Map m = [ 'val1', 'val2' ].inject( [:] ) { map, val -> map."$val" = a."$val" ; map }render m as JSON

To exclude properties, you would need to do something like this (UNTESTED)

def exclude = [ 'val3' ]Map m = new DefaultGrailsDomainClass( MyClass.class ).properties.findAll {  !( it.name in exclude )}.inject( [:] ) { map, val ->  map."$val.name" = a."$val.name" ; map}render m as JSON