使用条件运算符在 Grails 中呈现“作为 JSON"无法正确呈现 [英] Rendering 'as JSON' in Grails with conditional operator doesn't render correctly
问题描述
今天在 Grails 2.0.4 中尝试将对象列表呈现为 JSON 时遇到了这个奇怪的结果......(我知道我会后悔因为我眼皮底下的东西而问这个......更新 5/26,我的预测是正确的,见下文:-))
Came across this strange result today trying to render a list of objects as JSON in Grails 2.0.4...(i know i'm gonna regret asking this on account of something right under my nose...updated 5/26, my prediction was correct, see below :-))
这很好用;JSON 在浏览器中正确呈现...
This works fine; the JSON renders correctly in the browser...
def products = [] //ArrayList of Product objects from service
def model = (products) ? [products:products] : [products:"No products found"]
render model as JSON
...那么为什么这个没有 model
的缩短版本不起作用?
..so why doesn't this shortened version without model
work?
def products = []
render ((products) ? [products:products] : [products:"No products found"]) as JSON
上述代码的结果 JSON 作为单行文本输出,所以我怀疑它没有选择 as JSON
,但它的括号正确,所以有什么关系?
The resulting JSON from the above code is output as a single line of text, so I suspect it's not picking up as JSON
, but it's parenthesized correctly, so what's the deal?
['products':[com.test.domain.Product : null,com.test.domain.Product...]
['products':[com.test.domain.Product : null, com.test.domain.Product...]
推荐答案
这是 render
的正常行为.当您为 render
提供参数而没有像
This is a normal behavior of render
. When you provide arguments to render
without braces like
将模型渲染为 JSON
它进行了隐式调整,将 content-type
设置为 text/json
.但是在后一种情况下,您在不知不觉中使 render
使用大括号,例如 [mark on the first括号 after render
使 render 使用正常的 render()
]
It makes an implicit adjustment setting up the content-type
to text/json
. But in the later case, you have unknowingly made the render
to use the braces like [mark on the first brace after render
makes render use the normal render()
]
将 ((products) ? [products:products] : [products:"No products found"]) 渲染为 JSON
.
在上述情况下,您必须将命名参数传递给 render
提及 contentType
、text
或 model
、status
等.所以为了在浏览器/视图中将内联控制逻辑呈现为 JSON,您必须执行以下操作:
In the above case, you have to pass in the named parameters to render
mentioning the contentType
, text
or model
, status
etc. So in order to render the inline control logic as JSON in browser/view you have to do like below:
render(contentType: "application/json", text: [products: (products ?: "No products found")] as JSON)
您也可以使用 content-type
作为 text/json
.我更喜欢 application/json
.
You can also use content-type
as text/json
. I prefer application/json
.
更新
最简单的替代方法:render([products: (products ?: "No products found")] as JSON)
这篇关于使用条件运算符在 Grails 中呈现“作为 JSON"无法正确呈现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!