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

raf*_*ian 5 grails groovy json rendering

今天遇到了这个奇怪的结果,试图在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
Run Code Online (Sandbox Code Playgroud)

..那为什么没有这个缩短版本没有model工作?

def products = []       
render ((products) ? [products:products] : [products:"No products found"]) as JSON
Run Code Online (Sandbox Code Playgroud)

上面代码生成的JSON作为单行文本输出,所以我怀疑它没有提升as JSON,但是它的括号是正确的,那么交易是什么?

['products':[com.test.domain.Product:null,com.test.domain.Product ...]

dma*_*tro 8

这是正常的行为render.当你提供render没有大括号的参数时

render model as JSON

它使一个隐含的调整了设置content-typetext/json.但是在后一种情况下,你已经在不知不觉render中使用了像[在第一个支撑上的标记后render使渲染使用正常render()]

render ((products) ? [products:products] : [products:"No products found"]) as JSON.

在上述情况下,你必须在指定的参数传递给render提了contentType,text或者model,status等,所以为了使浏览器中内嵌的控制逻辑JSON /查看您所要做的象下面这样:

render(contentType: "application/json", text: [products: (products ?: "No products found")] as JSON)
Run Code Online (Sandbox Code Playgroud)

你也可以使用content-typeas text/json.我更喜欢application/json.

更新
替代最简单的方法:
render([products: (products ?: "No products found")] as JSON)

  • 这也可行:`render((产品?[产品:产品]:[产品:"没有找到产品"])作为JSON)` (4认同)
  • @JamesKleeh再次:`渲染([产品:(产品?:"没有找到产品")]作为JSON)` (2认同)