【问题标题】:JSON output of a view in GrailsGrails 中视图的 JSON 输出
【发布时间】:2010-05-03 12:35:46
【问题描述】:

好的,我在 Grails 中创建了一个非常简单的应用程序。 我有一个使用自动 Grails 脚手架生成的域类 (Person) 及其生成的控制器:

package contacts

class PersonController {

    def scaffold = Person

}

现在我想获得一个 Person 对象的 JSON 表示。

我必须更改视图或控制器吗?怎么做?

谢谢。

【问题讨论】:

    标签: json grails controller


    【解决方案1】:

    将以下内容添加到您的控制器:

    def list = {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        def personList = Person.list(params)
        withFormat {
            html {
                [personInstanceList: personList, personInstanceTotal: Person.count()]
            }
            json {
                render personList as JSON
            }
        }
    }
    

    这应该支持您的脚手架和 JSON 输出。

    您可以通过以下方式访问脚手架:

    http://localhost:8080/contacts/person/list

    您可以使用 json 格式访问 Person 列表:

    http://localhost:8080/contacts/person/list?format=json

    还有其他方法可以做到这一点,但我喜欢这样做,以便将脚手架留在周围进行测试。

    【讨论】:

    • 太棒了。感谢您准确而全面的回答;)
    • 对我来说有点太复杂了:你应该在你的控制器中使用static responseFormats = ["json","html"] 并保持生成的代码不变(比如respond User.list(params) ...)。无需编写代码来处理格式。遗憾的是我们应该能够使用脚手架和 json 而无需生成任何控制器代码
    猜你喜欢
    • 1970-01-01
    • 2017-04-24
    • 2018-07-28
    • 1970-01-01
    • 1970-01-01
    • 2017-07-16
    • 2019-12-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多