【问题标题】:How to render complex JSON with Grails 1.2 dynamically?如何使用 Grails 1.2 动态渲染复杂的 JSON?
【发布时间】: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 

【问题讨论】:

    标签: json grails


    【解决方案1】:

    我发现 JSON 构建器很难使用来获得所需的结果,所以 I prefer to generate the results in maps and lists and then render those

    通过具有以下内容(警告:未经测试的代码!):

    def results = []
    Authors.list()?.each{ author ->
        def authorResult = [id:author.id, name:author.name]
        Book.findAllByAuthor(author)?.each { book ->
            authorResultput('books', [id:book.id, name:book.name])
        }
        results << authorResult
    }
    def authors = [authors: results]
    render authors as JSON
    

    我认为你使代码更易于阅读和重用,它应该做你想做的事(我的错别字允许)。

    如果您总是要以相同的 JSON 格式呈现您的作者和书籍,您可以考虑使用registering a custom JSON object marshaller in Bootstrap.groovy。总之,类似的东西会起作用:

        JSON.registerObjectMarshaller(Author) {
            def returnArray = [:]
            returnArray['id'] = it.id
            returnArray['name'] = it.name
            return returnArray
        }
    

    还拥有您的作者的书籍属性会让事情变得更容易!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-17
      • 2017-07-01
      • 1970-01-01
      • 2017-06-05
      • 1970-01-01
      • 1970-01-01
      • 2012-03-27
      • 1970-01-01
      相关资源
      最近更新 更多