【发布时间】: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