【问题标题】:Using Groovy JSON builder使用 Groovy JSON 构建器
【发布时间】:2013-12-17 16:09:53
【问题描述】:

我见过几个非常酷的 Groovy 和 Grails JSON 构建器示例。这是一个: http://www.objectpartners.com/2012/03/22/grails-protip-dynamically-creating-json-in-grails-2-0-with-jsonbuilder/

现在我正在使用控制器使用 collect 生成测试列表,然后将列表呈现为 JSON 对象。有谁知道如何将上述示例放入控制器中?

这是我的控制器的样子:

class TreeMapController {

def list(){

    def results = myDomain.list()

    def test = [:] //Test List

    test=[] 

    def i = 0 //index key for parent

    //Generate list for fancyTree
    for (record in results){
        test.add([key:i++,folder:true, title: record.name, guid: record.id,
                children:record.subResults.collect{[title:it.name]}

        ])
    }

    //render response types
    withFormat {
        html test
        json {render test as JSON}
        xml {render test as XML}
    }
}

}

要使用 json 请求调用它,我提供了链接:localhost/project/list.json 如果我要调用上面提供的示例(使用 JSON 构建器的链接),我将如何调用或发出请求。

【问题讨论】:

  • 不确定我是否理解最后一段中的问题?
  • 我想说的是,使用我创建的上述控制器,要访问我使用链接 localhost/project/list.json 的 JSON 文件。但是,如果我要使用 JSON builder,我将如何提供指向 json 文件的链接。
  • 你的意思是像json {render builder.toString()}
  • 是的,我会试试的。抱歉,我是 Grail's 的新手,没有经过培训就被投入其中。
  • 不用担心 :-) 希望我们能提供帮助 :-)

标签: json grails groovy grails-controller


【解决方案1】:

您绝对应该看看Grails Documentation 以了解基本概念

这里,你有一个控制器会响应${baseUrl}/treeMap/list url,也就是说http://localhost:8080/treeMap/list 默认情况下

我认为,您必须请求带有 Content-type: text/json; 标头的 URL 才能使其工作

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-15
    • 2016-05-12
    • 1970-01-01
    相关资源
    最近更新 更多