在我的项目中,我试图将所选元素作为JSON从请求的参数返回。
域类:
class Component{
String name
String level
.
.
.
}
我有像
这样的http请求http://localhost:8080/myapp/component/showJson?name=name
所以我应该只返回
{
name:xyz
}
如果我的要求是
http://localhost:8080/myapp/component/showJson?name=name&level=level
然后我应该回来
{
name:xyz
level:1
}
任何建议都表示赞赏。
更新了JSON(多级)
[
{"name":"one","level":0,"
componentTypes":[
{"name":"one one","level":1,
"componentTypes":[
{"name":"one one one","level":2,"componentTypes":[]}
]
},
{"name":"one two","level":1,"componentTypes":[]}
]
},
{"name":"two","level":0,"componentTypes"[]},
{"name":"three","level":0,"componentTypes":[]}
]
class ComponentType {
String name
Integer level
static hasMany = [componentTypes:ComponentType]
ComponentType parent
static constraints = {
parent nullable:true
}
static mapWith = "mongo"
}
控制器操作
componentTypeList = ComponentType.createCriteria().list(){
eq("level", 0)
}
答案 0 :(得分:2)
您可以将params贴图与对象属性贴图相交并返回结果。我没有尝试过这个,但我无法想到它无法运作的原因。
def properties = component.properties;
def result = properties.subMap(params.keySet())
render result as JSON
<强>更新强>
class ComponentType {
.
.
.
def toJSON(def params) {
def properties = this.properties
def result = properties.subMap(params.keySet())
if(this.componentTypes) {
result.componentTypes = componentTypes*.toJSON(params)
}
result
}
}
def componentTypeList = ComponentType.createCriteria().list(){ eq("level", 0) }
render componentTypeList*.toJSON(params) as JSON