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"}
项目中我的用法:
似乎可以使用collect方法进行
User.list().collect{ it.part(....) }
这是对于单个实例的使用,没有什么问题。但是假如对于一个集合,有没有什么更加优雅的方式来处理呢? 比如我使用 User.findAllByXXX() as JSON 查询出来一个集合的对象作为JSON返回,这是否有更加好的方式来获得JSON的部分内容呢?