Grails Domain返回部分属性的JSON,支持关联属性.
改进groovyq的这篇文章:
http://www.groovyq.net/content/%E8%BF%94%E5%9B%9E%E9%83%A8%E5%88%86doaminclass#comment-179
感谢groovyq对Grails新人的指点.
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] grailsApplication.domainClasses.each{ domainClass -> /** * 添加取domain部分属性的功能 * 参数[include:[],except:[],relationship:[]] */ domainClass.metaClass.part = {m=[:]-> def map= [id:delegate.id] if(m.'include'){ m.'include'.each{ map[it] = delegate."$it" } }else{ domainClass.persistentProperties.each{ if(!(m.'except' && it.name in m.'except') && !(it.name in excludedProps) && !it.isAssociation()){ map[it.name]= delegate."${it.name}" } } } m.'relationship'?.each{key,value=null-> def mapKey = value?:key key.split(/\./).each{propName-> map[mapKey] = (map[mapKey]?:delegate)."$propName" } } return map }
使用方法:
def instance = SomeDomain.get(0);
//输出所有的非关联属性,以及指定的关联的某几个属性
instance.part( relationship:['bureau.id','bureau.name','bureau.code'] ) as JSON
//{id:1,"code":"AA","descript":null,"floorHeight":null,"floorLoad":null,"floorNo":null,"name":"AAA","bureau.id":0,"bureau.name":"A","bureau.code":"AAA"}
//仅输出指定的非关联属性以及指定的关联属性
instance.part(
include:['code','name'],
relationship:['bureau.name']
)
//{"id":0,code:"aaa","name":"AAA","bureau.name":"A"}
//输出除了id和name外的所有非关联属性以及指定的关联属性.
instance.part(
except:['name'],
relationship:['bureau.name']
)
//{id:0,"code":"AA","descript":null,"floorHeight":null,"floorLoad":null,"floorNo":null,"bureau.name":"A"}
//指定关联属性的命名.
instance.part(
except:['name'],
relationship:['bureau.id':'bureauId','bureau.name':'bureauName']
)
//{id:0,"code":"AA","descript":null,"floorHeight":null,"floorLoad":null,"floorNo":null,"bureauId":"A","bureauName":"A"}
上一篇: Markdown学习第一天
下一篇: 认识markdown第一天