【发布时间】:2017-06-02 13:19:16
【问题描述】:
我正在使用 gson 和网络配置文件。
我的域是:
package json
import grails.rest.*
@Resource(readOnly = false, formats = ['json', 'xml'])
class Hero {
String name
String data
String relation
Book book
static hasMany = [children: Hero]
我的控制器是:
package json
import grails.rest.*
import grails.converters.*
class HeroController extends RestfulController {
static responseFormats = ['json', 'xml']
HeroController() {
super(Hero)
}
def show(Hero hero){
respond hero
}
}
我的儿子:
hero.gson
import json.Hero
model {
Hero hero
}
json tmpl.hero(hero)
_hero.gson
import json.Hero
model {
Hero hero
}
json {
//data hero.data
id hero.id
data(relation: hero.relation)
name hero.name
children g.render(hero.children)
}
如果我使用 restful 配置文件运行它,那么所有子节点都会正确呈现。 如果我使用网络配置文件,则只会呈现两层深度。
我的预期结果是:
{
"id": 4,
"data": {
"relation": "e"
},
"name": "e",
"children": [{
"id": 2,
"data": {
"relation": "c"
},
"name": "c",
"children": [{
"id": 1,
"data": {
"relation": "b"
},
"name": "b",
"children": []
}
]
}
是否可以进行一对多的 json 渲染(与 restful 配置文件一样)? 有没有办法控制渲染的深度?
附:我阅读了文档,这部分对我来说不是很清楚:
如果您希望将作者作为渲染的一部分, 有两个要求,首先你必须确保关联 已初始化。
如果render方法遇到代理,就不会遍历到 关系以避免 N+1 查询性能问题。相同 适用于一对多集合关联。如果协会有 未初始化的渲染方法将不会遍历 收藏!
因此,您必须确保您的查询使用连接:
Book.findByTitle("The Stand", [fetch:[author:"join"]])
其次,在调用渲染方法时,你应该通过 deep 论据:
json g.render(book, [deep:true])
【问题讨论】:
标签: json grails one-to-many profile