gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 16:01:06 25 4
gpt4 key购买 nike

今天遇到了这个奇怪的结果,试图在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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com