grails.converters.JSON except few properties

Bella picture Bella · May 9, 2011 · Viewed 8.4k times · Source

I am using grails-1.3.2 and hbase-0.2.4.

I have the following domain class:

class MyClass{
  String val1
  String val2
  String val3

   //----

 }

class MyClassController{
    def someAction = {
        def myClass = new MyClass()
        //----

        String valAsJson = (myClass as JSON)

        render valAsJson 
     }
}

My question is, is any short way render only part of properties(for example render all except val3 property) ?

Answer

Nirmal picture Nirmal · May 9, 2011

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 Events

class 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.