【发布时间】:2023-03-20 15:31:01
【问题描述】:
我想渲染一个复杂类型,使用 Grails 中的 JSON 渲染方法,类似于下面的 JSON 输出:
{
"authors": [{
"id": 1,
"name": "Author 1",
"books": [{
"id": 1,
"name": "Book 1"
}, {
"id": 2,
"name": "Book 2"
}]
}, {
"id": 2,
"name": "Author 2",
"books": [{
"id": 1,
"name": "Book 1"
}, {
"id": 2,
"name": "Book 2"
}]
}]
}
我已经尝试使用以下代码执行此操作,其中 Author 和 Book 是包含属性 id 和 name 的域类,并且 Author hasMany Books(关联)。
def results = Authors.list()
render(contentType:"text/json") {
authors = array {
for(a in results) {
author id:a.id, name:a.name, books: array = {
def bookresults = Book.findAllByAuthor(a)
for(b in bookresults) {
book id:b.id, name:b.name
}
}
}
}
}
仅与作者一起工作正常,但当我尝试遍历每个作者的书籍并渲染它们时,代码会失败。
有什么想法吗?
使用最终代码更新问题
感谢 Dave 的回答,我最终得到了以下按预期工作的代码:
def authors = []
for (a in Author.list()) {
def books = []
def author = [id:a.id, name:a.name, books:books]
for (b in Book.findAllByAuthor(a)) {
def book = [id:b.id, name:b.name]
books << book
}
authors << author
}
def items = [authors:[authors]]
render items as JSON
【问题讨论】: