欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Grails Domain返回部分属性的JSON,支持关联属性.

程序员文章站 2022-05-19 21:42:24
...

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

 

 

 

相关标签: Grails json .net