json - 使用条件运算符在Grails中渲染 'as JSON'无法正确渲染

标签 json grails groovy rendering

今天遇到了这个奇怪的结果,试图在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中,并提及contentTypetextmodelstatus等。因此,为了在浏览器/ 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/

相关文章:

grails - 如何在Grails中从页面链接到另一个页面

grails发布插件错误 "class not found loading plugin resource [spring.resources]"

recursion - Groovy::Map Find Recursive

grails - Grails-多个下拉框值

json - 如何在flutter中将Json数据传递到另一个屏幕

ios - JSON 解析结果在 nsrray obj c 中的 nscfarray

python - 将嵌套的 json(mixpanel api 原始数据导出)转换为 CSV? (最好在 Python 中)

java - 我的 json "key"有 "String"类型值。如何判断接收到的字符串是 "link"还是 "simple string"?

json - 用Grails 2.4解析JSON空字符串值

java - 调用 Stage.show() 引发无法捕获的异常