今天遇到了这个奇怪的结果,试图在Grails 2.0.4中将对象列表呈现为JSON ...(我知道我会后悔由于我 Nose 底下的东西而问这个问题... 更新了 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
的这个简化版本不起作用?def products = []
render ((products) ? [products:products] : [products:"No products found"]) as JSON
上面代码生成的JSON作为单行文本输出,因此我怀疑它没有选择
as JSON
,但是正确地将其括起来,这是怎么回事?['products':[com.test.domain.Product : null, com.test.domain.Product...]
最佳答案
这是render
的正常行为。当您为render
提供参数而没有大括号时render model as JSON
它进行隐式调整,将content-type
设置为text/json
。但是在后一种情况下,您在不知不觉中使render
使用了括号,例如[[render
使render使用常规render()
之后的第一个括号上的标记]render ((products) ? [products:products] : [products:"No products found"]) as JSON
。
在上述情况下,您必须将命名参数传递到render
中,并提及contentType
,text
或model
,status
等。因此,为了在浏览器/ View 中将内联控制逻辑呈现为JSON,您必须执行以下操作:
render(contentType: "application/json", text: [products: (products ?: "No products found")] as JSON)
您也可以将
content-type
用作text/json
。我更喜欢application/json
。更新
另一种最简单的方法:
render([products: (products ?: "No products found")] as JSON)
关于json - 使用条件运算符在Grails中渲染 'as JSON'无法正确渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30678089/