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"}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值