今天遇到了这个奇怪的结果,试图在Grails 2.0.4中将对象列表呈现为JSON …(我知道我会后悔由于我鼻子底下的东西而问这个问题…… 已更新 5/26,我的预测是正确的,请参见下文:-))
这很好用;JSON在浏览器中正确呈现…
def products = [] //ArrayList of Product objects from service def model = (products) ? [products:products] : [products:"No products found"] render model as JSON
..so为什么缩短的版本没有model工作?
model
def products = [] render ((products) ? [products:products] : [products:"No products found"]) as JSON
上面代码生成的JSON作为单行文本输出,因此我怀疑它没有被拾取as JSON,但是正确地加上了括号,这是怎么回事?
as JSON
[‘products’:[com.test.domain.Product:null,com.test.domain.Product …]
这是的正常行为render。当您提供render无括号的参数时
render
render model as JSON
进行隐式调整以设置content-typeto text/json。但是,在后一种情况下,你已经在不知不觉中进行的render使用像括号[标记的第一支撑后render品牌呈现正常使用的render()]
content-type
text/json
render()
render ((products) ? [products:products] : [products:"No products found"]) as JSON。
render ((products) ? [products:products] : [products:"No products found"]) as JSON
在上述情况下,你必须在指定的参数传递给render提了contentType,text或者model,status等于是为了使在线控制逻辑JSON在浏览器/查看您所要做的象下面这样:
contentType
text
status
render(contentType: "application/json", text: [products: (products ?: "No products found")] as JSON)
您还可以使用content-type作为text/json。我更喜欢application/json。
application/json
更新 最简单的方法: render([products: (products ?: "No products found")] as JSON)
render([products: (products ?: "No products found")] as JSON)