我们正在尝试使grails 2.5项目在grails 3.3中工作
我们有一个JSON API,即contolers,它因此会以JSON进行响应:
log.info("about to return json")
render(status: 200, contentType: 'application/json') {
[
'result': 9999,
'message': "hello"
]
}
问题在于输出总是“{}”。这是 Controller 方法的最后代码。
如果我们这样做:
render("hello")
我们得到“你好”。
如果这样做:
render(status: 200, contentType: 'application/json') {
result = 0
player = "hello"
}
我们也总是得到“{{}”,这似乎很疯狂!
有任何想法吗?这在grails 3.3中被打破了吗?相同的代码在grails 2.5中可以完美地工作
当前,我们唯一能找到的解决方案是使用字符串连接来手工呈现JSON,这很乏味且容易出错。
最佳答案
仔细研究源代码,似乎grails 3已将负责JSON呈现的类更改为StreamingJsonBuilder。它的语法略有不同,破坏了现有的2.5代码。可悲的是,渲染文档和示例仍然具有“旧”格式。
有两种选择:
1使用新格式,例如:
render(status: 200, contentType: 'application/json') {
result 0
player "hello"
}
这样做的缺点是它不适用于自定义对象编码器。
2使用JSONBuilder,例如
def builder = new JSONBuilder()
def json = builder.build {
result= "0"
player= "hello"
}
render(status: 200, contentType: 'application/json', text: json)
这有两个优点:它适用于Grails 2.5和3.x,因此可以适用于grails4.x。此外,它还可以与Object Marshallers一起使用,从而节省了大量代码。
自定义对象编码器如下所示:
DecimalFormat df = new DecimalFormat("##0.00");
JSON.registerObjectMarshaller(Account) {
return [balance: df.format(it.balance), currencyIso: it.currencyIso, id: it.id]
}
并将它们放在bootstrap.groovy中(将其从conf移到init并在3.x中提供了另一个包)
关于json - grails 3.3呈现JSON损坏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45120854/